java:不能从静态上下文中引用非静态变量错误

以下代码在变量上产生了错误,con2说 "non-static variable con2 cannot be referenced from a static context Error."我用Google搜索解决方案,并且他们暗示尚未初始化该变量以使方法可用。我初始化不正确吗?我也尝试过将事情改为公开,但这也无济于事。

import java.io.*;

import java.net.*;

import java.sql.*;

import java.sql.CallableStatement;

import java.sql.ResultSet;

import java.sql.PreparedStatement;

import net.sourceforge.jtds.jdbcx.JtdsDataSource;

import net.sourceforge.jtds.jdbc.Driver;

class testconnect {

private java.sql.Connection con2 = null;

private final String url2 = "jdbc:jtds:sqlserver://";

private final String serverName= "SQL01";

private final String portNumber = "2677";

private final String databaseName= "App";

private final String userName = "bob";

private final String password = "boob";

private final String selectMethod = "cursor";

private String getConnectionUrl2(){

System.out.println("initalizing jtds");

//String returnVal = url+serverName+":"+portNumber+";databaseName="+databaseName+";user="+userName+";password="+password+";instance="+instance+";";

String returnVal = url2+serverName+":"+portNumber+"/"+databaseName+";user="+userName+";password="+password;

System.out.println("url2: " + returnVal);

return returnVal;

}

public static void main (String[] args) {

con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());

}

} //end class

回答:

不,实际上,你必须声明con2字段为静态:

private static java.sql.Connection con2 = null;

编辑:更正,实际上是远远不够的,你将遇到相同的问题,因为getConnection2Url方法也不是静态的。更好的解决方案可能是改为进行以下更改:

 public static void main (String[] args) { 

new testconnect().run();

}

public void run() {

con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());

}

以上是 java:不能从静态上下文中引用非静态变量错误 的全部内容, 来源链接: utcz.com/qa/416795.html

回到顶部