Danny Chang Danny Chang - 14 days ago 4
Java Question

executeQuery ERROR for JDBC

Hi I'm new to JDBC and ran into

executeQuery
error while constructing the JDBC. I just want to display all the information in the
student
table. I used the
prepareStatement
and I didn't set any parameter since I don't have. It works when use
createStatement
.

This is the error I'm getting

The method executeQuery(String) in the type Statement is not applicable for the arguments ()


How can I get it working using
prepareStatement
.

public class Test3 extends JFrame{

Vector rowData,columnNames;
JTable jt = null;
JScrollPane jsp = null;

Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;

//constructor
public Test3() {
columnNames = new Vector();
rowData = new Vector();

columnNames.add("Student_ID");
columnNames.add("Name");
columnNames.add("Gender");
columnNames.add("Age");
columnNames.add("DOB");
columnNames.add("Major");

try {
//1. Get a connection to database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false","root","1972");

//2. Create a prepareStatement
myStmt = myConn.prepareStatement("Select * from student");

// 3. Set the parameters
// no need to set the parameters, because there is not parameter needed to be set

// 4. Execute SQL query
***myRs = myStmt.executeQuery();***

while(myRs.next()) {
Vector col = new Vector();
col.add(myRs.getString(1));
col.add(myRs.getString(2));
col.add(myRs.getString(3));
col.add(myRs.getInt(4));
col.add(myRs.getString(5));
col.add(myRs.getString(6));

rowData.add(col);
}

} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(myRs!=null) myRs.close();
if(myStmt!=null) myStmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

public static void main(String[] args) {
Test3 test3 = new Test3();
}

}

Answer

You used the wrong method. For Statement, the definition of executeQuery is ResultSet executeQuery(String sql) throws SQLException; For PreparedStatement, the difinition is ResultSet executeQuery() throws SQLException;

So you can either use PreparedStatement myStmt = null; or myRs = ((PreparedStatement )myStmt).executeQuery();