有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在与给定值相同的记录中找到值

我试图给MySQL一个值,我希望它搜索记录,找到具有该值的记录,并在同一记录中获得一个特定值(在本例中为ID

Example:

|ID|Name|

ID is "5" and name is "Lapino"

我如何将“Lapino”传递给MySQL,让它搜索该记录并返回ID

谢谢, L


共 (3) 个答案

  1. # 1 楼答案

    必须使用PreparedStatement执行SELECTSQL语句:

    Connection conn = /*defined elsewhere*/;
    String name = /*defined elsewhere*/;
    
    int id;
    String sql = "select ID from MyTable where Name = ?";
    try (PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setString(1, name);
        try (ResultSet rs = stmt.executeQuery()) {
            if (! rs.next())
                throw new IllegalArgumentException("Not found: " + name);
            id = rs.getInt("ID");
            if (rs.next())
                throw new IllegalArgumentException("Multiple rows found: " + name);
        }
    }
    System.out.println(id); // Yay!
    
  2. # 2 楼答案

    如果我理解正确,您想找到ID值与请求值匹配的记录吗?要查找ID等于1234的记录,请执行以下操作:

    SELECT * FROM tbl WHERE ID = 1234
    
  3. # 3 楼答案

    首先创建一个jdbc连接,然后使用语句执行所需的查询

        Connection conn =
       DriverManager.getConnection("jdbc:mysql://localhost/test?" +
                                   "user=vikas&password=123");
        Statement stmt = conn.createStatement();
        ResultSet   rs = stmt.executeQuery("SELECT * FROM table WHERE ID=some_val");