【问题标题】:How can I find a value in the same record as the given value [closed]如何在与给定值相同的记录中找到值[关闭]
【发布时间】:2015-10-06 17:50:15
【问题描述】:

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

例子:

|ID|名称|

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

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

谢谢, 升

【问题讨论】:

  • “这可能吗”的答案几乎总是“是”。您为什么不举一个您正在搜索的记录的示例,您为尝试完成任务而编写的代码,并就您遇到的任何问题提出具体问题?
  • 使用 SQL。这就是结构化查询语言,它用于从关系数据库表中查询数据。这正是您所要求的。
  • 顺便说一句,这是所有数据库(关系、对象、NoSQL 等)的非常重要的特性。如果这不可能,那么数据库有什么用处?

标签: java mysql jdbc


【解决方案1】:

您必须使用PreparedStatement 执行SELECT 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!

【讨论】:

  • 这成功了!感谢您的帮助。
【解决方案2】:

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

SELECT * FROM tbl WHERE ID = 1234

【讨论】:

    【解决方案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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多