执行SQL查询时的MySQL语法错误 [英] MySQL syntax error when executing SQL query

查看:111
本文介绍了执行SQL查询时的MySQL语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行下面的代码时,我得到:

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

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获取在'?'附近使用的正确语法.在第1行`

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++;
}

请帮助我.

推荐答案

您将必须从executeQuery调用中删除query参数.如果提供该参数,则将在不绑定任何值的情况下执行查询(请参见

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.

执行如下查询:

ResultSet rst = st.executeQuery();

请注意:您应始终用 try-with-resources 块包装ConnectionPreparedStatementResultSet,例如

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
}

这样,无论发生什么情况,您都可以确保ResultSet将被关闭.

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

这篇关于执行SQL查询时的MySQL语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆