-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());
}
它試圖插入它意味着你的邏輯錯誤。雖然已經存在值 – soorapadman