是这样的,这里有个方法,参数是Dictionary<int,double>类型,int 类型是要修改记录的id,double类型是要在表中cnt字段的原值上相加的,我需要批量修改test表的cnt字段,想使用insert into ... on duplicate key update语句,但不行呀,有没有其他方法呢
举例说明要求, 比如ID=1时,CNT+1?
分2条SQL执行, UPDATE、INSERT
OR INSERT INTO test4(id,cnt) VALUES (167,2), (4,3), (6,5), (7,9) ON DUPLICATE KEY UPDATE id = VALUES(id), cnt= VALUES(cnt)+ cnt
update test t1,test t2 set t1.cnt=t1.cnt+1 where t1.id=t2.id;
这里有个方法(C#代码的,做Java的也能看懂) public int UpdateCnts(Dictionary<int,double> cnts){ //生成sql StringBuilder sb = new StringBuilder(); int i = 1; foreach(KeyValuePair<int, double> kv in cnts){ sb.append("update test set cn t= cnt + "+kv.Value+" where id = "+kv.Key); if (i != soldCnts.Count) { sb.Append(";"); } i++; } //执行sql DbBase db = new DbBase(); int res = db.ExecCommand(sb.ToString()); db.Close(); return res; } 这里用笨方法生成一条一条语句,如果参数集合比较大,语句就多了,执行效率低。听说mysql有批量修改的语句insert into ... on duplicate key update,但它好像只能直接修改为某值,而不能在原值加上某一个值不知道您看不看得明白
是这样的,这里有个方法,参数是Dictionary<int,double>类型,int 类型是要修改记录的id,double类型是要在表中cnt字段的原值上相加的,我需要批量修改test表的cnt字段,想使用insert into ... on duplicate key update语句,但不行呀,有没有其他方法呢
比如ID=1时,CNT+1?
UPDATE、INSERT
INSERT INTO test4(id,cnt) VALUES
(167,2),
(4,3),
(6,5),
(7,9)
ON DUPLICATE KEY UPDATE id = VALUES(id), cnt= VALUES(cnt)+ cnt
public int UpdateCnts(Dictionary<int,double> cnts){
//生成sql
StringBuilder sb = new StringBuilder();
int i = 1;
foreach(KeyValuePair<int, double> kv in cnts){
sb.append("update test set cn t= cnt + "+kv.Value+" where id = "+kv.Key);
if (i != soldCnts.Count) {
sb.Append(";");
}
i++;
}
//执行sql
DbBase db = new DbBase();
int res = db.ExecCommand(sb.ToString());
db.Close();
return res;
}
这里用笨方法生成一条一条语句,如果参数集合比较大,语句就多了,执行效率低。听说mysql有批量修改的语句insert into ... on duplicate key update,但它好像只能直接修改为某值,而不能在原值加上某一个值不知道您看不看得明白