2012-01-11 42 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(); 
} 
相關問題