Reputation: 3013
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
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
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
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
Reputation: 62603
You can do that in four steps.
select count(1) from table where column = 34343
will do.PreparedStatement
s in Java.ResultSet
.Upvotes: 1