gpt4 book ai didi

java - 如何在executeQuery方法中编写sql查询?

转载 作者:行者123 更新时间:2023-11-29 09:32:07 30 4
gpt4 key购买 nike

我有一个带有 userId 字段的 account_holder 表,并且有一个数据集作为 data。我只想从 account_holder 中选择 userId 为 data[3] 的记录,即(4 个字段数据集)。我将查询编写为:

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("select * from account_holder where userID = 'data[3]' ");

但是我的 rs 为 null 该条目无法进入 ResultSet 对象 rs。请告诉我在executeQuery()方法中使用where子句编写sql查询的正确方法。

最佳答案

正如第一篇文章所说,这是处理此问题的一种方法:

     try {
Statement statement = connection.createStatement(); // Creating Statement

// Executing Statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM account_holder WHERE userID = '" + data[3] + "'");

// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");

// Clean up
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}

但在您的上下文中,我实际上建议使用 PreparedStatement:

    try {
// Making statement
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM account_holder WHERE userID = ?");
preparedStatement.setString(1, data[3]); // Set String for the first question mark in Query

ResultSet resultSet = preparedStatement.executeQuery(); // Executing the Prepared Statement

// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");

// Clean up
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}

关于java - 如何在executeQuery方法中编写sql查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472682/

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