Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

jdbc - MySQL syntax error when executing SQL query

When I try to run the code below I am getting:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1`

String query="Select * from DB.Admin where username = ?";
PreparedStatement st=connection.prepareStatement(query);
st.setString(1,request.getParameter("loginid"));
ResultSet rst= st.executeQuery(query);
int count=0;
while(rst.next()){
   count++;
}

Please help me in this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will have to remove the query argument from your executeQuery call. If you provide the parameter, the query will be executed without binding any values (see Statement for details) - this is why the syntax (i.e. the ?) is invalid.

Execute the query like this:

ResultSet rst = st.executeQuery();

As a side note: you should always wrap Connection, PreparedStatement and ResultSet with a try-with-resources block, e.g.

try (ResultSet rst = st.executeQuery()) {
    // read the results
}

This way you can be sure the ResultSet will be closed no matter what happens.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...