-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