【问题标题】:C# DataTable update Access DatabaseC# DataTable 更新 Access 数据库
【发布时间】:2014-01-08 14:46:27
【问题描述】:

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

【问题讨论】:

  • 如果您在Watch Window 中发出dataTable.GetChanges(),您有什么变化吗?
  • 这个方法对另一个函数有用,但对这个没有用。谢谢

标签: c# database ms-access datatable oledb


【解决方案1】:

假设你对datatable做了一些改动,那么你可以通过这种方式将生成的update/insert/delete命令传递给适配器

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

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

【讨论】:

  • 很好,史蒂夫,当我阅读 GetDeleteCommand() 行时,我错过了 OP 没有分配命令的事实!
  • 是的! “无法添加您想要的数据量。字段太小。插入或粘贴的数据较少。”
  • 嗯,这是另一个问题。它是由插入到表的列之一中的值生成的。这个(可能是文本列)的大小不足以包含用户在输入框中输入的数据(需要修剪或设置最大长度)
  • 我建议发布一个新问题,它会比这个答案中的评论更受关注。
猜你喜欢
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
相关资源
最近更新 更多