您好,我有一个类,它包含一个执行查询的action,如下所示
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();
它不像我想象的那样工作。我有个未定义的错误。。我该怎么解决?
最佳答案
该错误表示,db
对“MysqlConnect”的引用没有createStatement
方法。你需要一个连接对象。使您的connectToAndQueryDatabase
返回连接对象
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);