如果我的表有一个具有特定主键值的记录,我如何从使用JDBC的Java程序中找到答案?我可以在发出ResultSet
声明之后以某种方式使用SELECT
吗?
答案 0 :(得分: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;
}
取自here。
答案 1 :(得分:3)
您可以执行类似
的操作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();
}
答案 2 :(得分:1)
您可以分四步完成。
select count(1) from table where column = 34343
这样的东西会。PreparedStatement
。ResultSet
。答案 3 :(得分:1)
select case
when exists (select 1
from table
where column_ = '<value>' and rownum=1)
then 'Y'
else 'N'
end as rec_exists
from dual;
答案 4 :(得分:0)
此链接应该与您想要的内容类似:Check if record exists