我的方法目前选择所有的教师和他们的ID从数据base.In我selectDBT
可变的,我要定义这样一种方式,即要求用户输入串并返回匹配用的ID从数据库
SELECT name, id from instructor where name like substring;
并且这substring
应该是用户可以输入的一些'%sub%'
子字符串。
private static void selectInstructor() throws SQLException {
Connection dataConnection = null;
Statement statement = null;
String selectDBT = "SELECT name, id from instructor";
try {
dataConnection = getConnection();
statement = dataConnection.createStatement();
System.out.println(selectDBT);
ResultSet result_set = statement.executeQuery(selectDBT);
while (result_set.next()) {
String ins_name = result_set.getString("name");
String ins_id = result_set.getString("id");
System.out.println("Instructor Name : " + ins_name);
System.out.println("Instructor ID : " + ins_id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dataConnection != null) {
dataConnection.close();
}
}
}
到目前为止,我能够让用户把他们的用户名和密码用java swing界面输入数据库。现在我想创建另一个界面,用户可以输入substring
,这应该参考一些%sub%
字符串模式匹配,我的输出将是与子字符串匹配的名称和ID。现在我',获取所有名称和ID的无论如何,因为我不让用户输入子字符串匹配。也硬编码将无法正常工作,因为我希望用户动态选择。
编辑:用事先准备好的声明:
private static void selectInstructor() throws SQLException {
Connection dataConnection = null;
Statement statement = null;
// String selectDBT = "SELECT name, id from instructor";
try {
dataConnection = getConnection();
PreparedStatement preparedStatement =
dataConnection.prepareStatement("SELECT name, id from instructor where name like ?");
preparedStatement.setString(1, substring);
// statement = dataConnection.createStatement();
System.out.println(preparedStatement);
ResultSet result_set = statement.executeQuery(preparedStatement);
while (result_set.next()) {
String ins_name = result_set.getString("name");
String ins_id = result_set.getString("id");
System.out.println("Instructor Name : " + ins_name);
System.out.println("Instructor ID : " + ins_id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dataConnection != null) {
dataConnection.close();
}
}
}
但是,我得到相同的输出。请注意,我在SQL中非常新。我很乐意使用来自答案建议的准备好的语句。
问题在哪里,您是否试图解决错误或想要知道如何实现? –
在第二次尝试中,您需要使用'preparedStatement.executeQuery()',而不是'statement.executeQuery(preparedStatement)';那甚至不会编译。 –