我有一个小问题。我编写了一个方法,其中有一个 SQL 查询,应该在 2 个参数后输出正确的字符串。然而,在调试时,结果不是正确的元素。我不知道为什么会发生这种情况。
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
我要求提供用户名和 template_id,我只想从模板列中获取一个元素。 SQL 查询是正确的。我已经测试过了。但查询似乎遍历具有相同用户名的所有元素。结果,我只得到最后一个元素,而不是正确的元素。
更新
最佳答案
目前您在查询中不使用方法参数。正如已经建议的,您应该使用 PreparedStatement
来解决这个问题。您基本上应该执行以下操作:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
如果您不使用 PreparedStatement
并按照注释中的建议手动构建查询,您的应用程序可能容易受到 SQL 注入(inject)攻击。
关于java - 如何从 SQL 数据库中仅获取 1 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759288/