C#将dataset中的表写入数据库问题。求支招

yinyi4120 2014-08-20 06:46:16
在dataset中添加了多个datetable表,并把从串口接收过来的数据放在表中(串口有多个,所以讲数据存在不同的表中了),
同时在sql数据库中也建立了表名相同的表,现在要将dataset各个表中的数据库放入SQL数据库中对应的表中,该如何解决。
求大神指点下,并贴点代码!
...全文
441 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
save4me 2014-08-20
  • 打赏
  • 举报
回复
SqlDataAdapter更新方法adapter.Update(数据集, 数据集中数据表名),下面是通过DataGridView提交更新数据集到数据库的示例

public DataSet DsCustomer;
public BindingSource BsCustomer;
private const string connstr = @"Data Source=(local);User Id=sa;Password=123456;Initial Catalog=Database";
public static DataSet getDataSet(string connStr, string sql, string name)
{
	SqlConnection conn = null;
	DataSet ds = null;
	try
	{
		conn = new SqlConnection(connStr);
		ds = new DataSet();
		conn.Open();

		SqlDataAdapter cmd = new SqlDataAdapter(sql, conn);
		cmd.Fill(ds, name);
	}
	catch
	{
	}
	finally
	{
		if (conn != null)
			conn.Close();
	}
	return ds;
}

public void UpdateDB()
{
	try {
		
		DsCustomer = new DataSet();
		DsCustomer = getDataSet(connstr, "select * from Customer", "Customer");
		
		SqlConnection conn = new SqlConnection(connstr);
		conn.Open();

		SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customer", conn);
		
		SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
		
		adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
		adapter.InsertCommand = commandBuilder.GetInsertCommand();
		
		adapter.Fill(DsCustomer);
		
		BsCustomer = new BindingSource();
		BsCustomer.DataSource = DsCustomer.Tables["Customer"];
		System.Diagnostics.Debug.Print("DS1 Rows:" + DsCustomer.Tables[0].Rows.Count.ToString());
		dataGridView1.DataSource = BsCustomer;//这里把dataGridView1的DataSource指向BindingSource

		DataRowView drv = BsCustomer.AddNew() as DataRowView;//如果是添加新记录的话
		drv.BeginEdit();//开始修改
		drv["Name"] = "fish";//该行item属性为“fish”
		drv["type"] = "2";//该行item属性为“fish”
		drv.EndEdit();
		//结束BindigSource编辑
		BsCustomer.EndEdit();
		//获取修改过的记录来只更新有改变的数据
		//DsCustomer.GetChanges();
		//System.Diagnostics.Debug.Print("DS1 Rows:" + DsCustomer.Tables[0].Rows.Count.ToString());
		//System.Diagnostics.Debug.Print("Changed: " + DsCustomer.HasChanges().ToString());

		adapter.Update(DsCustomer, "Customer");
		//真正更新到数据库
		//DsCustomer.AcceptChanges();
	} catch (Exception) {
		throw;
	}
}
EdsionWang 2014-08-20
  • 打赏
  • 举报
回复
SqlDataAdapter的Update(DataTable); http://msdn.microsoft.com/zh-cn/library/z1z2bkx2.aspx

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧