gpt4 book ai didi

执行SQL查询时MySQL语法错误

转载 作者:行者123 更新时间:2023-11-29 11:36:00 24 4
gpt4 key购买 nike

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

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 参数。如果您提供参数,则将在不绑定(bind)任何值的情况下执行查询(有关详细信息,请参阅 Statement) - 这就是语法(即 ?)无效的原因。

像这样执行查询:

ResultSet rst = st.executeQuery();

作为旁注:您应该始终使用 try-with-resources 包装 ConnectionPreparedStatementResultSet em> block ,例如

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

这样您就可以确保无论发生什么情况ResultSet都会关闭。

关于执行SQL查询时MySQL语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com