首页 新闻 会员 周边

源数据库到目标数据库的插入和更新

0
悬赏园豆:10 [已解决问题] 解决于 2013-08-19 16:31

想把一个SQL的查询结果写到新的目标数据里。代码如下:

其中command.text 就是 Select * from Region;

然后目标数据库里,表结构与源表一样,只有一行记录,然后设置了主键自动增加。

但是现在的代码不能把源数据写进去。

求教如何改正?

 

private void btnSave_Click(object sender, EventArgs e)

{

 

string serverName = textBoxTargetServer.Text;

 

var dbName = comboBoxTargetDatabase.SelectedItem as string;

 

string conStr= "Data Source= " + serverName + ";Initial Catalog=" + dbName + ";Integrated Security=True";

 

SqlCommand cmd = new SqlCommand();

 

using (SqlConnection conn = new SqlConnection(conStr))

{

cmd.Connection = conn;

cmd.CommandType = CommandType.Text;

cmd.CommandText = textBox1.Text;

cmd.Connection.Open();

SqlDataAdapter sda = new SqlDataAdapter(textBox1.Text, conn);

SqlCommandBuilder cb = new SqlCommandBuilder(sda);

sda.InsertCommand = cb.GetInsertCommand();

sda.DeleteCommand = cb.GetDeleteCommand();

sda.UpdateCommand = cb.GetUpdateCommand();

targetDataSet = new DataSet();

sda.Fill(targetDataSet);

 

DataTable dtTarget = targetDataSet.Tables[0];

 

DataTable dtSource = sourceDataSet.Tables[0];

 

for (int i = 0; i < sourceDataSet.Tables[0].Rows.Count; i++)

{

 

DataRow sourceRow = sourceDataSet.Tables[0].Rows[i];

dtTarget.ImportRow(sourceRow);

}

sda.Update(targetDataSet);

}

cmd.Parameters.Clear();

cmd.Connection.Close();

Seajay的主页 Seajay | 初学一级 | 园豆:184
提问于:2013-08-19 03:45
< >
分享
最佳答案
1

在 dtTarget.ImportRow(sourceRow); 之后加上:

dtTarget.Rows(i).SetAdded();

参考:update is not working with importrow

收获园豆:10
dudu | 高人七级 |园豆:30994 | 2013-08-19 10:39

这句话加上之后还是提示:Violation of PRIMARY KEY constraint, Cannot insert duplicate key in Object 'dbo.region'

是不是还要加些主键的判断啊?

Seajay | 园豆:184 (初学一级) | 2013-08-19 15:52

搞定了,谢谢dudu!

Seajay | 园豆:184 (初学一级) | 2013-08-19 16:30
其他回答(1)
0

我认为 在原表Region查询时 排出主键就没问题了

Sam G. | 园豆:218 (菜鸟二级) | 2013-08-19 13:26
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册