【发布时间】:2021-03-03 22:25:41
【问题描述】:
我正在尝试使用 update() 方法,但它正在将我的数据表数据插入到我的数据库中,而不检查该行是否存在,因此它正在插入重复数据。它也不会删除数据表中不存在的行。如何解决这个问题?我想将我的数据表与服务器表同步。
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'MyDatabaseDataSet11.Vendor_GUI_Test_Data' table. You can move, or remove it, as needed.
this.vendor_GUI_Test_DataTableAdapter.Fill(this.MyDatabaseDataSet11.Vendor_GUI_Test_Data);
// read target table on SQL Server and store in a tabledata var
this.ServerDataTable = this.MyDatabaseDataSet11.Vendor_GUI_Test_Data;
}
插入
private void convertGUIToTableFormat()
{
ServerDataTable.Rows.Clear();
// loop through GUIDataTable rows
for (int i = 0; i < GUIDataTable.Rows.Count; i++)
{
String guiKEY = (String)GUIDataTable.Rows[i][0] + "," + (String)GUIDataTable.Rows[i][8] + "," + (String)GUIDataTable.Rows[i][9];
//Console.WriteLine("guiKey: " + guiKEY);
// loop through every DOW value, make a new row for every true
for(int d = 1; d < 8; d++)
{
if ((bool)GUIDataTable.Rows[i][d] == true)
{
DataRow toInsert = ServerDataTable.NewRow();
toInsert[0] = GUIDataTable.Rows[i][0];
toInsert[1] = d + "";
toInsert[2] = GUIDataTable.Rows[i][8];
toInsert[3] = GUIDataTable.Rows[i][9];
ServerDataTable.Rows.InsertAt(toInsert, 0);
//printDataRow(toInsert);
//Console.WriteLine("---------------");
}
}
}
尝试更新
// I got this adapter from datagridview, casting my datatable to their format
CSharpFirstGUIWinForms.MyDatabaseDataSet1.Vendor_GUI_Test_DataDataTable DT = (CSharpFirstGUIWinForms.MyDatabaseDataSet1.Vendor_GUI_Test_DataDataTable)ServerDataTable;
DT.PrimaryKey = new DataColumn[] { DT.Columns["Vendor"], DT.Columns["DOW"], DT.Columns["LeadTime"], DT.Columns["DemandPeriod"] };
this.vendor_GUI_Test_DataTableAdapter.Update(DT);
【问题讨论】:
-
填充数据表的代码在哪里?
-
如果您已经从数据库中加载了行,则更新只进行更新而不是插入。否则它不知道它的存在。
-
@DaleK 从数据库中加载行是什么意思,您能详细说明一下吗?
-
正是如此,您使用
Fill()方法和select语句从数据库加载数据。您修改该数据,包括添加新行并将其更新回来。如果您在前端创建所有数据,这可能会重复现有数据,那么您的适配器不知道这一点,因为您尚未加载任何数据,因此它假定它是全新的。 -
@DaleK 从技术上讲这并不完全正确 - 如果数据行的状态为已修改,Update() 将执行更新,这与它的出处无关
标签: c# sql-server datatable datagridview