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

时间:2015-10-06 17:50:16

标签: java mysql jdbc

我正在尝试给MySQL一个值,我希望它能够搜索记录,找到具有该值的记录并在同一记录中获取特定值(在这种情况下 ID

  

示例:

     

| ID |名称|

     

ID为“5”,名称为“Lapino”

我怎样才能将“Lapino”传递给MySQL并让它搜索该记录并让它返回ID?

谢谢, →

3 个答案:

答案 0 :(得分:1)

您必须使用SELECT执行PreparedStatement SQL语句:

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!

答案 1 :(得分:0)

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

SELECT * FROM tbl WHERE ID = 1234

答案 2 :(得分:0)

首先创建一个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");