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();
它不工作,就像我所料。我收到一個未定義的錯誤..我該如何解決這個問題?
向我們展示你的錯誤日誌 – Infinity
貴MysqlConnect類具有的createStatement()? – laksys
無關注:'con = null;'不關閉連接。它泄漏它們。你會很快耗盡可用的連接。 –