无法从静态上下文中引用非静态 变量错误

tjficcbw tjficcbw 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我做了个数据库的操作类,总是调不好,谢谢各位,帮个忙给调试一下,代码如下。


import java.sql.*;

public class SqlHelper {



public Connection con = null;
public ResultSet result = null;

public void SelectException (String SelectSqlString) {


try{
// 为这个连接建立SQL语句容器
Statement select = con.createStatement();
// Statement select = con.prepareStatement( );//用于复杂的SQL语句

// 执行SQL语句查询获得字符集
ResultSet result = select.executeQuery(SelectSqlString);
} catch (Exception e) {
System.out.println(SelectSqlString);// 看SQL语句查过来没
e.printStackTrace();
}
}


public void CloseConn(){
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}



public void SetConn() {
// 定义数据库地址
String url = "jdbc:mysql://localhost:3306/ccentertainment";
// 定义数据库连接
//Connection con = null;
try {
// 定义数据库驱动
String driver = "com.mysql.jdbc.Driver";
// 加载数据库驱动
Class.forName(driver).newInstance();
} catch (Exception e) {
System.out.println("加载数据库驱动失败!");
return;
}
try {
// 连接数据库
con = DriverManager.getConnection(url, "root", "root");
}catch (Exception e) {
e.printStackTrace();
}
}
}
#########################################################

import java.sql.*;

public class ShowDbTest {

ResultSet Sresult = null;

public static void main(String args[]) {
SqlHelper ShValue = new SqlHelper();
ShValue.SetConn();
ShValue.SelectException("select * from user");
Sresult = ShValue.result;
try {
while (Sresult.next()) { // process results one row at a time
System.out.println(Sresult.getInt(1) + Sresult.getInt(2));
}
}

catch (Exception e) {
e.printStackTrace();
}
ShValue.CloseConn();
}
}

#############################################

---------- 编译 ----------
ShowDbTest.java:11: 无法从静态上下文中引用非静态 变量 Sresult
Sresult = ShValue.result;
^
ShowDbTest.java:13: 无法从静态上下文中引用非静态 变量 Sresult
while (Sresult.next()) { // process results one row at a time
^
ShowDbTest.java:14: 无法从静态上下文中引用非静态 变量 Sresult
System.out.println(Sresult.getInt(1) + Sresult.getInt(2));
^
ShowDbTest.java:14: 无法从静态上下文中引用非静态 变量 Sresult
System.out.println(Sresult.getInt(1) + Sresult.getInt(2));
^
4 错误

输出完成 (耗时 1 秒)

...全文

相关推荐

评论 13
收藏 已收藏
分享
返回顶部
tjficcbw
Java SE 62,621 成员 307,251 内容