2012-12-11 35 views
1

为什么我不能在构造函数外执行查询?我不能使用我在构造函数中声明的变量。为什么不?我必须将数据库连接放在带参数的方法中吗?我不能在构造函数外使用数据库连接,为什么?

public class main extends javax.swing.JFrame 
{ 
    DefaultListModel model = new DefaultListModel(); 

    public main() 
    { 
     initComponents(); 
     try 
     { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "password"); 
      Statement stat = con.createStatement(); 
      ResultSet resultaat = stat.executeQuery(query); 

      while (resultaat.next()) 
      { 
       model.addElement(resultaat.getString(2)); 
      } 
     } 
     catch (Exception ex) 
     { 
      System.out.println(ex); 
     } 
    } 
} 

回答

2

con是withing构造函数范围。使用

Connection con;

为类变量,并在构造函数中

con = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password"); 

使用此而已。对所需变量做同样的事情。你需要在整个课堂中使用。

+0

确定感谢信息被盗。 – Suranga

+0

不客气 – Suranga

2

我不能用我在构造函数中声明的变量。为什么不?

因为它们在构造函数中被声明为限于该范围。你不能在你的构造函数之外访问它们。如果您想在构造函数外使用它们,请将它们设置为实例变量,您应该首先执行这些操作。

你的类应该像这样的事情:

public class DBConnection { 
    Connection con=null; 
    public DBConnection() { 
    initComponents(); 
    try { 
     conn = DriverManager.getConnection("jdbc:mysql://localhost/project","root","password"); 
    } 
    catch(SQLException ex) { 
    } 
    } 

    public void doDBOps() { 
    String yourQuey="whatever"; 
    PreparedStatement stmnt = this.conn.preparedStatement(yourQuery); 
    ResultSet rs = stmnt.executeQuery(); 
    //rest of your code 
    } 
} 
0

方法或构造函数中定义的变量仅限于该范围。如果你想初始化一个变量并在整个班级中使用它,你必须把它变成一个班级字段(因此,将它的范围扩大到班级本身),按照惯例,定义一个get和/或set方法。

0

看来你总体上看的是数据库的单例类。您可以在其他类中使用此类来访问现有连接,而不是每次都使用DriverManager工厂来获取新的连接对象。

下面将样品无耻地从here

public class DBConnectionSingleton 
{ 
    private static DBConnectionSingleton instance = null; 
    private static Connection conn; 
    private DBConnectionSingleton() 
    { 
    String dbDriver = .. 
    String url = .. 
    String username= .. 
    String password = .. 
    try 
    { 
     Class.forName(dbDriver); 
     conn = DriverManager.getConnection(url, username, password); 
    } 
    catch (ClassNotFoundException cnfErr) 
    { 
     cnfErr.printStackTrace(); 
    } 
    catch (SQLException err) 
    { 
     err.printStackTrace(); 
    } 
    } 

    public static DBConnectionSingleton getInstance() 
    { 
    if (instance == null) 
     return new DBConnectionSingleton(); 
    else 
     return instance; 
    } 
    public static Connection getConnection() 
    { 
    return conn; 
    } 
} 
+0

它看起来像这个例子中的单例'实例'从未初始化...? – Krease

相关问题