使用Java填充SQL表中的特定列

时间:2010-10-23 16:37:15

标签: java sql mysql jdbc insert

基本上,我有一个方法来处理从表中获取的数据,以创建一个新对象“ZExpert”。 ZExpert具有参数int id,int domain和double ZExpert。我在表中添加了一个列,我从名为“Z_Expert_Score”的数据中获取了数据。

我想将Z_Expert_Score列中对象的双ZExpert分数放在“Customer_Expert_ID”= domain且“Customer_ID”= id的行中。这是我的尝试

ZExpert[] allZExpert = scrCalc.getzExpertAll();

for(int i = 0; i < allZExpert.length; i++) {
  ZExpert currentZExpert = allZExpert[i]; 
  int id = currentZExpert.getId();
  int domain = currentZExpert.getDomain();
  double ZExpertScore = currentZExpert.getzExpert();

  Statement statement = conn.createStatement();
  statement.executeUpdate ("INSERT INTO CONSUMER_EXPERT_ID 
                             where CONSUMER_EXPERT_ID="+domain+"AND CONSUMER_ID="+id+ "(Z_EXPERT_SCORE) VALUES("+ZExpertScore+")");
}

提前致谢!

2 个答案:

答案 0 :(得分:2)

您需要使用update SQL statement,而不是插入。

UPDATE CUSTOMER_TABLE SET Z_EXPERT_SCORE = ? WHERE CONSUMER_EXPERT_ID= ? AND CONSUMER_ID= ?

另外,您应该使用PreparedStatement,而不是将Strings组合在一起来创建SQL语句。

ZExpert[] allZExpert = scrCalc.getzExpertAll();

for(int i = 0; i < allZExpert.length; i++) {
  ZExpert currentZExpert = allZExpert[i]; 
  int id = currentZExpert.getId();
  int domain = currentZExpert.getDomain();
  double ZExpertScore = currentZExpert.getzExpert();

  String sql = "UPDATE CUSTOMER_TABLE SET Z_EXPERT_SCORE = ? WHERE CONSUMER_EXPERT_ID= ? AND CONSUMER_ID= ?";
  PreparedStatement statement = con.prepareStatement(sql);
  statement.setDouble(1, zExpertScore);
  statement.setInt(2, domain);
  statement.setInt(3, id);
  statement.executeUpdate();
}

答案 1 :(得分:0)

如果您要扩充已存在的行,则需要使用UPDATE语句。