2017-09-05 42 views
-2

我創建一個循環來更新股票價格到我的數據庫。如果代碼存在於表上,程序將更新數據。如果代碼不存在於表上,程序將INSERT數據。java更新數據到數據庫錯誤

運行時,第一個代碼存在於我的表中,但程序捕獲到一個異常「重複鍵入主鍵'」。在我的代碼中出現了什麼問題?

謝謝你的幫助。

for (int i = 0; i < jsonarray.length(); i++) { 
      JSONObject obj = jsonarray.getJSONObject(i); 
      String code = obj.getString("a"); 
      double lastprice = obj.getDouble("l"); 
      double change = obj.getDouble("k"); 
      double dayshigh = obj.getDouble("v"); 
      double dayslow = obj.getDouble("w"); 

      ResultSet rs = st.executeQuery(iName); 

      while (rs.next()) { 
       String hihi = rs.getString("iName"); 
       if (rs.getString("iName").equals(code)) { 
        String query = "UPDATE Duong SET LastPrice = ?, iChange = ?, DaysHigh = ?, DaysLow = ? where iName = ?"; 
        PreparedStatement preparedStmt = conn.prepareStatement(query); 
        preparedStmt.setDouble(1, lastprice); 
        preparedStmt.setDouble(2, change); 
        preparedStmt.setDouble(3, dayshigh); 
        preparedStmt.setDouble(4, dayslow); 
        preparedStmt.setString(5, code); 
        preparedStmt.executeUpdate(); 
       } else { 
        st.executeUpdate("INSERT INTO Duong " 
          + "VALUES ('" + code + "'," + lastprice + "," + change + "," + dayshigh + "," + dayslow + ")"); 
       } 

      } 

     } 
     conn.close(); 

    } catch (Exception e) { 
     System.err.println("Got an exception!"); 
     System.err.println(e.getMessage()); 
    } 
+0

它試圖插入它意味着你的邏輯錯誤。雖然已經存在值 – soorapadman

回答

0

查詢本身從數據庫中選擇丟失,但我認爲它返回多個結果。包含不同庫存符號的一行會導致您嘗試插入導致重複鍵錯誤的新行。