JDBC的executeQuery ERROR

时间:2016-11-23 00:54:30

标签: java database jdbc

您好我刚接触JDBC并在构造JDBC时遇到executeQuery错误。我只想显示student表中的所有信息。我使用prepareStatement并且我没有设置任何参数,因为我没有。它在使用createStatement时有效。

这是我遇到的错误

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

如何使用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();
    }

}

1 个答案:

答案 0 :(得分:1)

您使用了错误的方法。对于声明 executeQuery 的定义是  #include <ctime> 对于 PreparedStatement ,定义为ResultSet executeQuery(String sql) throws SQLException;

因此,您可以使用ResultSet executeQuery() throws SQLException;PreparedStatement myStmt = null;