0

I'm trying to retrieve some data from an SQL table using JDBC through the BufferedReader, the code I wrote for this execution:

System.out.println("Type a name");
    String nname = br.readLine();

        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/VetTest", "root", "root");
        Statement stmt=(Statement) con.createStatement();
        String query = "select * from Pet WHERE name LIKE '?%'";
        ResultSet rs=(ResultSet) stmt.executeQuery(query);

        while(rs.next()) 
            System.out.println(rs.getString("name"));

        if (petn.equals(query)) {
        System.out.println("Searching names.." + nname + query);
        }

I don't know if I'm doing it wrong, so to summarize my question, I'm trying to retrieve some data depend about what the user inputs in the console. E.g. I'm trying to search for the name Jack in my database I want my application to search for this person's name or a similar person name.

The result I always get when I enter a petname (even though the pet the name is available in my database):

No such a name

4

2 回答 2

4

你还没有告诉我们问题是什么,但我看到了一个问题:

WHERE name LIKE '?%'

这是不正确的。该条款应该是

WHERE name LIKE ?

你应该准备一个语句,绑定一个包含通配符 ( %) 的字符串,然后执行这个准备好的语句:

PreparedStatement stmt = con.prepareStatement("select * from Pet WHERE name LIKE ?");
stmt.setString(1, name + "%");
ResultSet rs = stmt.executeQuery();

阅读有关准备好的语句的教程

于 2013-11-03T14:31:48.717 回答
0

如果我没记错的话,您想搜索名称,该名称也可能是其他名称的一部分。例如,如果你输入 Jack

Jackson,Helen Jack 的值也应该从数据库中检索。然后将查询更改为

System.out.println("Type a name");
    String nname = br.readLine();

        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/VetTest", "root", "root");
        Statement stmt=(Statement) con.createStatement();
        **String query = "select * from Pet WHERE name LIKE '%nname%'";**
        ResultSet rs=(ResultSet) stmt.executeQuery(query);

        while(rs.next()) 
            System.out.println(rs.getString("name"));

        if (petn.equals(query)) {
        System.out.println("Searching names.." + nname + query);
        }
于 2013-12-06T17:22:02.337 回答