gpt4 book ai didi

java - 用户输入后输出数据库内容

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

我正在尝试执行一个语句,其中将提示用户输入作者姓名,然后将输出所有作者值,下面可以工作,但不会输出任何内容。

  public static void WhichAuthorQry (Connection conn)
{
Scanner sc = new Scanner(System.in);

try {

Statement stmt = (Statement) conn.createStatement();

System.out.println("Please enter the Authors name to search:");
String name = sc.next();

String SQL = "SELECT * FROM Poet WHERE PoetName='" + name + "'";

ResultSet rs = stmt.executeQuery(SQL);

while(rs.next()) {
System.out.println("Name: " + rs.getString("PoetName"));
System.out.println("Language: " + rs.getString("Language"));

}

}catch (Exception e){
System.out.println("ERROR: " + e.getMessage());
}


}

最佳答案

我建议将您的查询放入准备好的语句中,并允许用户使用通配符:

PreparedStatement ps = conn.prepareStatement("SELECT * FROM Poet WHERE PoetName like ?");
ps.setString(1,name);
ResultSet rs = ps.executeQuery() ;
while ( rs.next() ) {
System.out.println("Name: " + rs.getString("PoetName"));
System.out.println("Language: " + rs.getString("Language"));
}

关于java - 用户输入后输出数据库内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47243153/

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