您好我有这个包含actionPerformed的类来执行它看起来像这样的查询
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;
}
}
但问题出在
行Statement st = db.createStatement();
它不像我预期的那样有效。我得到一个未定义的错误..我该如何解决这个问题?
答案 0 :(得分: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);