2014-12-04 54 views
0

我有一個包含2列,名稱和分數的表。 我說它有10個有分數的名稱,如果新分數大於或等於表中的最低分數,我想用新名稱和分數替換最低分 的那一行。hsqldb - 如何替換我的Highscore(包含前10)表中的值

我設法得到最高值的結果集,但我沒有得到用我的新名稱和分數(在Java中)取代它。

String newName = "Test"; 
int score = 12345; 
ResultSet result; 
Statement stat = conn.createStatement(); 
result = stat.executeQuery("SELECT * FROM Highscore ORDER BY Score DESC"); 
result.next(); 
if(result.getInt(2) <= score) { 
    // enter code here 
} 
+0

帶「*替換該行*」你的意思是你想從數據庫中刪除,並插入一個新的? – 2014-12-04 11:32:04

+0

是的,如果我的新分數大於或等於最小分數,我想在我的表格中找到最低分數並刪除該分數並替換爲新名稱和分數。 – HowTheF 2014-12-04 13:06:19

回答

1

嘗試這樣的事情

  String newName = "Test"; 
      int score = 12345; 
      int newScore = 54321; 
      ResultSet result; 
      Statement stat = conn.createStatement(); 
      result = stat.executeQuery("SELECT * FROM Highscore ORDER BY Score ASC");// use DESC if u want to replace the highest value 
      result.next(); 
      if(result.getInt(2) <= score) 
      { 
       PreparedStatement preparedStatement = conn.prepareStatement("UPDATE Highscore SET Name =? Score = ? WHERE Score = ?"); 
       preparedStatement.setString(1, newName); 
       preparedStatement.setString(2, newScore); 
       preparedStatement.setString(3, result.getInt(2)); 
       int updateCount = preparedStatement.executeUpdate(); 
      } 
+0

Thx不得不把你的答案和cmd的答案結合起來,但是它得出了thx:D – HowTheF 2014-12-04 13:36:43

+0

歡迎你的朋友:) – KaustubhSV 2014-12-05 05:33:47

1
You can use following code to update lowest score record : 

String newName = "Test"; 
int score = 12345; 
ResultSet result; 
PreparedStatement ps = conn.prepareStatement("UPDATE Highscore SET NAME = ?, SCORE = ? WHERE SCORE = (SELECT MIN(SCORE) FROM Highscore)"); 
ps.setString(1, newName); 
ps.setInt(2, score); 
int updatedCount = ps.executeUpdate(); 
if(updatedCount>0) 
System.out.println("Record Successfully updated"); 
+0

忘了提及我想用新的名字和分數替換最低分的那一行,如果新分數大於或等於表格中的最低分數。 – HowTheF 2014-12-04 13:16:42

+0

但我解決了它與urs和KaustubhSV組合的答案。謝謝 – HowTheF 2014-12-04 13:55:15

相關問題