将DataTable更新为MySql数据库C# [英] Update DataTable to MySql database C#
问题描述
我有一个如下的DataTable MyDT:
I have a DataTable MyDT like below:
string MyConString = "SERVER=" + sConfig_hostname + ";" +
"DATABASE=" + sConfig_dbname + ";" +
"UID=" + sConfig_dbusername + ";" +
"PASSWORD=" + sConfig_dbpassword + ";Allow Zero Datetime=true;";
MySqlConnection connection = new MySqlConnection(MyConString);
string sQuery="Select * from Table";
connection.Open();
MySqlDataAdapter myDA = new MySqlDataAdapter(sQuery, connection);
myDA.SelectCommand.ExecuteNonQuery();
DataTable MyDT=new DataTable()// <- My DataTable
myDA.Fill(MyDT);
connection.Close();
...
...
// do something with MyDT
...
...
在使用MyDT做一些事情之后,我想将其更新到数据库,该怎么办?我已经在google中搜索了网页,但是几乎通过循环数据表进行了更新.有没有没有循环更新整个数据表的方法?请帮忙!感谢您的阅读
After do something with MyDT , I want to update it to the DataBase, how can I do it ?I have searched google for pages but almost update by looping the datatable. is there a way to update the whole datatable without loop?Please help! Thanks for reading
推荐答案
您需要配置DataAdapter的SelectCommand
,DeleteCommand
,UpdateCommand
和InsertCommand
属性.您可以使用MySqlCommandBuilder
填充三个命令对象(选择,删除,更新).
You need to configure SelectCommand
, DeleteCommand
, UpdateCommand
and InsertCommand
properties of DataAdapter. You may use MySqlCommandBuilder
to populate three command objects (Select, Delete, Update).
MySqlConnection connection = new MySqlConnection(MyConString);
string sQuery="Select * from Table";
MySqlDataAdapter myDA = new MySqlDataAdapter(sQuery, connection);
MySqlCommandBuilder cmb = new MySqlCommandBuilder(myDA);
DataTable MyDT = new DataTable()// <- My DataTable
myDA.Fill(MyDT);
//Add new rows or delete/update existing one
//and update the DataTable using
myDA.Update(MyDT);
这篇关于将DataTable更新为MySql数据库C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!