2012-12-25 46 views
1

你好,我有這樣的類,它包含的actionPerformed執行查詢它看起來像這樣數據庫的createStatement不能達到

MysqlConnect db = new MysqlConnect(); 

@Override 
public void actionPerformed(ActionEvent e) { 

    if(e.getSource() == openKnop) { 

      try { 

       db.connectToAndQueryDatabase("test", "root", "root"); 
       System.out.println("connection established"); 

       Statement st = db.createStatement(); 
       String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'"; 
       st.executeQuery(query); 

       System.out.println("Selected query succesfull"); 


      } catch (SQLException e1) { 
       e1.printStackTrace(); 
      } 
      finally { 
       db.closeCon(); 
        System.out.println("connection closed"); 
      } 
    } 

和我MysqlConnect();類如下所示

public class MysqlConnect{ 

    protected Connection con; 

    public void connectToAndQueryDatabase(String database, String username, String password) throws SQLException { 
     con = null; 
      try { 
       con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/" + database, 
            username, 
            password); 
      } catch (SQLException e) { 
       e.printStackTrace(); 
      } 
    } 

    public void closeCon() { 
     con = null; 
    } 
} 

,但問題是在該行

聲明ST = db.createStatement();

它不工作,就像我所料。我收到一個未定義的錯誤..我該如何解決這個問題?

+1

向我們展示你的錯誤日誌 – Infinity

+0

貴MysqlConnect類具有的createStatement()? – laksys

+0

無關注:'con = null;'不關閉連接。它泄漏它們。你會很快耗盡可用的連接。 –

回答

3

錯誤說db'MysqlConnect'的引用沒有createStatement方法。你需要一個Connection對象。讓你的connectToAndQueryDatabase返回Connection對象

public Connection connectToAndQueryDatabase(String database, String username, String password) throws SQLException { 
//your code 

return con; 
} 

和:

Connection conn = db.connectToAndQueryDatabase("test", "root", "root"); 
       System.out.println("connection established"); 

       Statement st = conn.createStatement(); 
       String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'"; 
       st.executeQuery(query); 
+0

謝謝!那就是我一直在尋找的:) – Reshad