为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3242003 2018-12-07 12:09:48
想把一个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();
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

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

dtTarget.Rows(i).SetAdded();

参考:update is not working with importrow

查看完整回答
反对 回复 2019-01-07
?
MM们

TA贡献1886条经验 获得超2个赞

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

查看完整回答
反对 回复 2019-01-07
  • 2 回答
  • 0 关注
  • 836 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信