我有一个account_holder表,其中有一个userId字段,并且有一个数据集作为数据。我只想从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查询的正确方法。
答案 0 :(得分:1)
正如第一篇文章所述,这是处理此问题的一种方式:
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();
}
答案 1 :(得分:0)
您只需要在executeQuery方法中更改查询
示例:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from account_holder where userID = '"+data[3]+"' ");
或者您也可以运行以下命令:
ResultSet rs = st.executeQuery("select * from account_holder where userID = "+data[3]+"");