如何将DataTable
保存到文件中。 accdb(Access)现有的?我使用了以下代码,但它不起作用:
using (OleDbConnection oledbConnection = new OleDbConnection(connection))
{
oledbConnection.Open();
string query = "SELECT * FROM Student";
using (OleDbCommand oledbCommand = new OleDbCommand(query, oledbConnection))
{
using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand))
{
using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter))
{
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
oledbDataAdapter.Update(dataTable);
}
}
}
oledbConnection.Close();
}
使用文件的原始内容初始化变量dataTable,然后通过添加一行来修改它,现在我必须更新数据库中的表。
我尝试使用以下代码,但这不起作用:(
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student", connection);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand(true);
// create and insert row in the DataTable
da.Update(dataTable);
答案 0 :(得分:4)
假设您已对数据表进行了一些更改,那么您可以通过这种方式将生成的update / insert / delete命令传递给适配器
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand();
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand();
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand();
oledbDataAdapter.Update(datatable);
现在适配器知道如何更新表