【发布时间】:2016-04-01 22:38:22
【问题描述】:
我想创建一个函数,它可以同时更新我的旧表并记录更改之前的数据。 (就像一个日志表。)我创建了一个表来检索我搜索的表和另一个存储更改之前的表。这两个表在列上有一些差异。 DS 是检索数据集,ADS 是只插入的日志数据集
private void Update_Button_Click(object sender, EventArgs e)
{
try
{
//Update table1
SqlCmb = new SqlCommandBuilder(SqlAd);
SqlAd.Update(DS, "dataset1");
//INSERT table1_log
DataSet ds = new DataSet();
ds = ADS;
ds.Tables[0].Columns.Add("USER_NAME", typeof(string));
ds.Tables[0].Columns.Add("UNIQ", typeof(String));
foreach (DataRow dr in ds.Tables[0].Rows)
{
dr["USER_NAME"] = Form1.USER_NAME.Text;
dr["ALTER_TIME"] = DateTime.Now;
}
SqlDataAdapter SqlAdI = new SqlDataAdapter("SELECT * FROM table1_log where 0 = 1", SqlCon);
SqlCommandBuilder SqlCmbI = new SqlCommandBuilder(SqlAdI);
SqlCom= new SqlCommand("INSERT INTO table1_log FROM" + ds.Tables[0], SqlCon) ;
SqlAdI.InsertCommand = SqlCom;
SqlAdI.Update(ADS, "table1");
MessageBox.Show("Info updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我的问题是它无法插入日志表,但更新到 table1 工作正常。 Uniq 是 PK 并由 sql server 自动生成。错误消息是“并发冲突:更新命令影响了预期的 1 条记录中的 0 条。”
谢谢!
【问题讨论】:
-
你有使用库的能力吗?如果可以的话,看看 dapper 会让你的生活更轻松
-
嗨 Konkked,你是什么意思?我可以成功更新到表1但不能插入table_log,所以我认为我有能力使用库。
-
@ericka08:您应该查找触发器。这是在更新另一个表时更新一个表的好方法。您可以将触发器添加到表中,以便它会自动更新您的日志表,而无需使用 SQLCommand 并跟踪代码中所做的更改。我们在工作中一直使用这些来以您正在寻找的相同方式更新日志表。我会尝试找到一个链接
-
@JSON 我正在使用 datagridview,我希望我能坚持下去。它使我的代码非常简单。我会看一下,但这将是我的最后一次尝试。谢谢!
标签: c# datagridview sqldataadapter