我正在开发一个使用 Access 数据库的项目。首先,我从 db 复制我需要的信息并将其放入 DataTable(结合 2 个表)。在这个数据表上我搜索项目;使用 GridView 更新、删除、添加行,所有这些都发生在 ajax 更新面板中。当我尝试将更改应用回数据库时会出现问题。我想要做的是获取 DataTable 的某些行并将它们更新/插入/删除到某些表的某些行。重要的是数据库表必须包含与 DataTable 相同的信息。我实际上不知道我是否可以通过这种方式使用 OledbDataAdapter.Update。
这是我得到的例外:并发冲突:UpdateCommand 影响了预期的 1 条记录中的 0 条。
我的代码:
void load_dtTable()
{
OleDbConnection bag = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Profiles\\StjBugraO\\Desktop\\data.accdb");
DataTable dtResult = new DataTable();
if (Session["dtResult"] != null)
{
dtResult = (DataTable)Session["dtResult"];
}
else
{
bag.Open();
try
{
OleDbDataAdapter adtr = new OleDbDataAdapter("select gt.NodeID, gt.unit_num,gt.unit_name_text,gt2.ip_id ,gt2.server_name_text ,gt.call_flow_type From gt inner join gt2 on gt.cm_id=gt2.cm_id", bag);
dtResult.Clear();
adtr.Fill(dtResult);
adtr.Dispose();
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "Şube Kodu";
dtResult.Columns[2].ColumnName = "Şube ADI";
dtResult.Columns[3].ColumnName = "IP Adresi";
dtResult.Columns[4].ColumnName = "Call Manager";
dtResult.Columns[5].ColumnName = "Santral Tipi";
foreach (DataRow dr in dtResult.Rows)
{
if ((string)dr[5] == "P")
{
dr[5] = "PRI";
}
else if ((string)dr[5] == "A") dr[5] = "ANALOG";
}
}
catch (Exception e)
{
}
Session["dtResult"] = dtResult as DataTable;
bag.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
DataTable dtResult = Session["dtResult"] as DataTable;
//changing the names of the columns (that i need) to be the same with the db
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "unit_num";
dtResult.Columns[2].ColumnName = "unit_name_text";
dtResult.Columns[3].ColumnName = "ip_id";
dtResult.Columns[5].ColumnName = "call_flow_type";
OleDbConnection bag = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Profiles\\StjBugraO\\Desktop\\data.accdb");
OleDbDataAdapter adtr2 = new OleDbDataAdapter("select NodeID ,unit_num ,unit_name_text , ip_id , call_flow_type from gt", bag);
OleDbCommandBuilder Ocmd = new OleDbCommandBuilder(adtr2);
adtr2.DeleteCommand=Ocmd.GetDeleteCommand();
adtr2.InsertCommand=Ocmd.GetInsertCommand();
adtr2.UpdateCommand=Ocmd.GetUpdateCommand();
DataTable dt = dtResult.GetChanges();
int updates = 0;
try
{
if(dt != null)
updates=adtr2.Update(dtResult);
}
catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
//changing them back
dtResult.Columns[0].ColumnName = "NodeID";
dtResult.Columns[1].ColumnName = "Şube Kodu";
dtResult.Columns[2].ColumnName = "Şube ADI";
dtResult.Columns[3].ColumnName = "IP Adresi";
dtResult.Columns[4].ColumnName = "Call Manager";
dtResult.Columns[5].ColumnName = "Santral Tipi";
Label2.Text = updates + "changes applied.";
adtr2.Dispose();
bag.Close();
}