简体   繁体   English

使用SqlDataAdapter.Update方法时复制表行

[英]Duplicating table rows when using SqlDataAdapter.Update Method

In my project I have table "Product". 在我的项目中,我有“产品”表。

ID  Name   Price
------------------  
1   xyz     100

2   abc     200

3   pqr     300

In my c# code I would like to update my table rows using SqlAdapter. 在我的C#代码中,我想使用SqlAdapter更新我的表行。 For that i crated a datatable 为此,我创建了一个数据表

DataTable dtTable=new DataTable("Product");

Add updated values to Datatable .That is, 将更新后的值添加到Datatable中。

ID  Name   Price
    ------------------  
    1   aaa     100

    2   bbb     200

    3   ccc     300

I used the following step to update table in database with this values 我使用以下步骤用此值更新数据库中的表

SqlConnection myLocalConnection = new SqlConnection(_ConnectionString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from " + dtTable.TableName, myLocalConnection);
 SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

     mySqlDataAdapter.Update(dtTable);

But when executing this update function, In database all tables are duplicated. 但是在执行此更新功能时,在数据库中所有表都是重复的。 that is 那是

ID  Name   Price
------------------  
1   xyz     100

2   abc     200

3   pqr     300

4   aaa     100

5   bbb     200

6   ccc     300

I only want to replace the existing data. 我只想替换现有数据。 Why these rows are duplicated in this table. 为什么这些行在此表中重复。 Please help 请帮忙

According to Updating Data Sources with DataAdapters you have to specify your update command by yourself and then you can call the Update function of the sql data adapter! 根据使用DataAdapter更新数据源,您必须自己指定update命令,然后才能调用sql数据适配器的Update函数!

SqlDataAdapter mySqlDataAdapter = 
     new SqlDataAdapter("Select * from " + dtTable.TableName, myLocalConnection);
dataAdpater.UpdateCommand = new SqlCommand("UPDATE ...", connection);
mySqlDataAdapter.Update(dtTable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM