使用dataadapter.update()
引起
违反并发性: UpdateCommand 影响了预期 1 条记录中的 0 条。
数据库表zwkmdzb
id int 主键 自增 非空
ZTBM smallint
NIAN smallint
KMDM varchar
KMMC
DYKMDM varchar
DYKMMC varchar
ZDDYBZ varchar
YSBZ varchar
代码
/// <summary>
/// 批量更新
/// </summary>
/// <param name="table">更新的数据</param>
/// <param name="batchSize">批量大小</param>
public void BatchUpdate(DataTable table, int batchSize)
{
connString = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};Character Set =gb2312",
ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["Prot"], ConfigurationSettings.AppSettings["DataBase"],
ConfigurationSettings.AppSettings["Uid"], ConfigurationSettings.AppSettings["Pwd"]);
try
{
conn = new MySqlConnection(connString);
myAdpt.UpdateCommand = new MySqlCommand("UPDATE zwkmdzb SET "
+ "DYKMDM=@DYKMDM,ZDDYBZ=@ZDDYBZ,DYKMMC=@DYKMMC,YSBZ=@YSBZ WHERE ZTBM=@ZTBM AND NIAN=@NIAN AND KMMC=@KMMC;", conn);
myAdpt.UpdateCommand.Parameters.Add("@DYKMDM", MySqlDbType.VarChar, 23, "DYKMDM");
myAdpt.UpdateCommand.Parameters.Add("@ZDDYBZ", MySqlDbType.VarChar, 20, "ZDDYBZ");
myAdpt.UpdateCommand.Parameters.Add("@DYKMMC", MySqlDbType.VarChar, 255, "DYKMMC");
myAdpt.UpdateCommand.Parameters.Add("@YSBZ", MySqlDbType.VarChar, 8, "YSBZ");
myAdpt.UpdateCommand.Parameters.Add("@ZTBM", MySqlDbType.Int16, 6, "ZTBM");
myAdpt.UpdateCommand.Parameters.Add("@NIAN", MySqlDbType.Int16, 6, "NIAN");
myAdpt.UpdateCommand.Parameters.Add("@KMMC", MySqlDbType.VarChar, 255, "KMMC");
myAdpt.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
myAdpt.InsertCommand = new MySqlCommand("INSERT INTO "
+ "zwkmdzb (ZTBM,NIAN,KMDM,KMMC,DYKMDM,ZDDYBZ,DYKMMC,YSBZ) VALUES(@ZTBM,@NIAN,@KMDM,@KMMC,@DYKMDM,@ZDDYBZ,@DYKMMC,@YSBZ);", conn);
myAdpt.InsertCommand.Parameters.Add("@ZTBM", MySqlDbType.Int16, 6, "ZTBM");
myAdpt.InsertCommand.Parameters.Add("@NIAN", MySqlDbType.Int16, 6, "NIAN");
myAdpt.InsertCommand.Parameters.Add("@KMDM", MySqlDbType.VarChar, 23, "KMDM");
myAdpt.InsertCommand.Parameters.Add("@KMMC", MySqlDbType.VarChar, 255, "KMMC");
myAdpt.InsertCommand.Parameters.Add("@DYKMDM", MySqlDbType.VarChar, 23, "DYKMDM");
myAdpt.InsertCommand.Parameters.Add("@ZDDYBZ", MySqlDbType.VarChar, 20, "ZDDYBZ");
myAdpt.InsertCommand.Parameters.Add("@DYKMMC", MySqlDbType.VarChar, 255, "DYKMMC");
myAdpt.InsertCommand.Parameters.Add("@YSBZ", MySqlDbType.VarChar, 8, "YSBZ");
myAdpt.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
myAdpt.DeleteCommand = new MySqlCommand("DELETE FROM zwkmdzb WHERE ZTBM=@ZTBM AND NIAN=@NIAN AND KMMC=@KMMC;", conn);
myAdpt.DeleteCommand.Parameters.Add("@ZTBM", MySqlDbType.Int16, 6, "ZTBM");
myAdpt.DeleteCommand.Parameters.Add("@NIAN", MySqlDbType.Int16, 6, "NIAN");
myAdpt.DeleteCommand.Parameters.Add("@KMMC", MySqlDbType.VarChar, 255, "KMMC");
myAdpt.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
myAdpt.Update(table);
}
catch (Exception)
{
}
finally
{
myAdpt.Dispose();
conn.Close();
}
}
最后 Update需要注意的是;防止并发性的操作。有在Update执行之前所包含的数据行有被修改,则会发生并发性操作错误。