如何检查JDBC中的MySql表中是否存在具有特定主键的记录

nik*_*kos 0 java mysql jdbc

如果我的表有一个具有特定主键值的记录,我如何从使用JDBC的Java程序中找到?ResultSet我发表SELECT声明后可以用某种方式吗?

npi*_*nti 5

Count对于这种情况可能是一个更好的主意.您可以像这样使用它:

public static int countRows(Connection conn, String tableName) throws SQLException {
    // select the number of rows in the table
    Statement stmt = null;
    ResultSet rs = null;
    int rowCount = -1;
    try {
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE.... ");
      // get the number of rows from the result set
      rs.next();
      rowCount = rs.getInt(1);
    } finally {
      rs.close();
      stmt.close();
    }
    return rowCount;
  }
Run Code Online (Sandbox Code Playgroud)

取自这里.