java:不能从静态上下文错误中引用非静态变量 [英] java : non-static variable cannot be referenced from a static context Error

查看:51
本文介绍了java:不能从静态上下文错误中引用非静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在变量 con2 上产生错误,说 不能从静态上下文错误中引用非静态变量 con2." 我在 Google 上搜索了解决方案他们建议变量尚未初始化以使方法可用.我是否错误地初始化了这个?我也尝试将内容更改为公开内容,但这也无济于事.

The following code is generating an error on the variable con2 saying "non-static variable con2 cannot be referenced from a static context Error." I Googled for a resolution and they are suggesting the variable isn't initalized yet to make the methods available. Am I initializing this incorrectly? I also tried changing things to public but that didn't help either.

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 字段声明为静态:

No, actually, you must declare your con2 field static:

private static java.sql.Connection con2 = null;

更正,实际上这还不够,您会遇到同样的问题,因为您的 getConnection2Url 方法也不是静态的.更好的解决方案可能是进行以下更改:

Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change:

 public static void main (String[] args) { 
     new testconnect().run();
 } 

 public void run() {
     con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
 }

这篇关于java:不能从静态上下文错误中引用非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆