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

时间:2017-11-11 21:51:08

标签: java mysql jdbc

我试图做一个声明,其中将提示用户输入作者名称,然后输出所有作者值,下面有效,但不输出任何内容。

  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());
     }


 }

2 个答案:

答案 0 :(得分:2)

我建议将您的查询放入预准备语句并提供用户使用通配符:

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"));
}

答案 1 :(得分:0)

我想到的最快的事情是,您输入的名称是否与PoetName匹配?

你可以尝试

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