nikos
nikos

Reputation: 3013

How to check if a record with a specific primary key exists in a MySql table from JDBC

How can i find out, from a Java program using JDBC if my table has a record with a specific primary key value? Can i use the ResultSet somehow after i issue a SELECT statement?

Upvotes: 0

Views: 13382

Answers (4)

duvo
duvo

Reputation: 1734

You can do something like

private boolean hasRecord(String id) throws SQLException {
    String sql = "Select 1 from MyTable where id = ?";  

    PreparedStatement ps = dbConn.prepareStatement(sql);
    ps.setString(1,id);
    ResultSet rs = ps.executeQuery();

    return rs.next();
}

Upvotes: 3

Dead Programmer
Dead Programmer

Reputation: 12585

select case 
            when exists (select 1 
                         from table 
                         where column_ = '<value>' and rownum=1) 
            then 'Y' 
            else 'N' 
        end as rec_exists
from dual;

Upvotes: 1

npinti
npinti

Reputation: 52185

Count might be a better idea for this case. You can use it like so:

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;
  }

Taken from here.

Upvotes: 5

adarshr
adarshr

Reputation: 62603

You can do that in four steps.

  1. Write SQL. Something like select count(1) from table where column = 34343 will do.
  2. Learn how to get connection using JDBC.
  3. Learn about PreparedStatements in Java.
  4. Learn how to read values from ResultSet.

Upvotes: 1

Related Questions