2012-01-11 18 views

回答

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

+0

我知道这是旧的文章,但是这并不甚至回答提出的问题。 – user1377392 2015-12-04 08:25:20

+0

@ user1377392:您正在计算满足给定条件的元素的数量。如果结果大于0,则存在。计数可能会更好,因为您没有返回整个结果集,因此数据传输很少。 – npinti 2015-12-04 08:30:26

1

你可以做,在四个步骤。

  1. 写入SQL。像select count(1) from table where column = 34343会做。
  2. 了解如何使用JDBC获取连接。
  3. 了解有关PreparedStatement s的Java文件。
  4. 了解如何从ResultSet中读取数值。
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; 
+0

只是辉煌!!!!应该被接受为答案。 Count(*)实际上需要很长时间,使用这个肯定会快得多。 – Algorithmist 2013-07-31 05:34:36

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(); 
} 
相关问题