gpt4 book ai didi

C# DataTable更新Access数据库

转载 作者:搜寻专家 更新时间:2023-10-30 21:59:38 24 4
gpt4 key购买 nike

如何将 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);

最佳答案

假设你对数据表做了一些修改,那么你可以通过这种方式将生成的更新/插入/删除命令传递给适配器

oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand();
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand();
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand();
oledbDataAdapter.Update(datatable);

现在适配器知道如何更新你的表了

关于C# DataTable更新Access数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com