2016-01-03 66 views
0

我試圖找到johnname列的數據庫,但我無法。如何在sql db中獲得結果項數量?

我試圖如下:

String st="SELECT name FROM mytable"; 
ResultSet rs = stmt.executeQuery(st); 
int icount = 0 ; 
if (rs.equals("john")) { 
    while (rs.next()) { 
     icount++; 
    } 
} 
jtext1.setText(String.valueOf(icount)); 

回答

0

你試圖檢查ResultSet對象等john串 - OFC它總是false。你需要的東西是這樣的:

String query = "SELECT name FROM mytable"; 
ResultSet rs = stmt.executeQuery(query); 
int johnCount = 0; 
while (rs.next()) { 
    String name = rs.getString("name"); 
    if ("john".equalsIgnoreCase(name)) { 
     johnCount++; 
    } 
} 

equalsIgnoreCase方法 - 我認爲這是你的情況更合適。不要忘記關閉您的ResultSet,Statement和區塊或使用try-with-resources

但是,如果您想在表中統計約翰,最好實際使用SELECT COUNT(*) FROM mytable WHERE name = 'john'。請注意,這是查詢中區分大小寫的情況。

+0

非常感謝您...... –

0
String st="SELECT name FROM mytable"; 
ResultSet rs = stmt.executeQuery(st); 
int icount = 0 ; 
while (rs.next()) { 
    if (rs.getString("name").equals("john")) { 
     icount++; 
    } 
} 
jtext1.setText(String.valueOf(icount)); 
+0

非常感謝您...... –

0

使用下面的代碼:

while(rs.next()){ 
    String name = rs.getString("name"); 
    if("john".equals(name)) 
     icount++; 
} 
jtext1.setText(String.valueOf(icount)); 
+0

非常感謝您...... –

0

你需要去在每一行與

while (rs.next) {.... 

而且你需要得到的值來比較像這樣

String name = rs.getString(1); 
If (name.equals("john")) {.... 

另一種選擇是改變任務做計數這是更高效的。

select count(name) from myTable where name = 'john'; 
+0

應該rs.getString (1)如果您有興趣獲得第一列。 –

+0

非常感謝你... –

+0

沒問題,如果你喜歡的答案投票:) –

1

只是另一種方式....

int count = 0; 
String query = "SELECT COUNT(DISTINCT name) AS rCount FROM myTable " 
      + "WHERE UPPER(name) LIKE UPPER('JOHN');" 
ResultSet rs = stmt.executeQuery(query); 
while (rs.next()) { count = rs.getInt("rCount"); } 
System.out.println(count);