2012-12-11 34 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

相關問題