从DataTable向Access Table添加行

时间:2014-01-08 19:15:52

标签: c# database datatable oledb

我已经使用此代码从我的Access表格中创建DataTable

DataTable dataTable = new DataTable();
...
using (OleDbConnection oledbConnection = new OleDbConnection(connection))
{
   oledbConnection.Open();
   using (OleDbCommand oledbCommand = new OleDbCommand("SELECT * FROM Student", oledbConnection))
   {
       using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand))
       {
          oledbDataAdapter.Fill(dataTable);
       }
   }
}

我后来通过插入带有此代码的新行来更改数据表。

DataRow dataRow = dataTable.NewRow();
dataRow["FirstName"] = "John";
dataRow["LastName"] = "Connor";
dataTable.Rows.Add(dataRow);
dataTable.GetChanges();

如何在访问数据库中进行此更改? 以下代码是否正确?

using (OleDbConnection oledbConnection = new OleDbConnection(connectionString))
{
   OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter();
   oledbDataAdapter.SelectCommand = new OleDbCommand(queryString, oledbConnection);
   OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter);
   connection.Open();
   oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
   oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
   oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
   oledbDataAdapter.Update(dataTable);
   connection.Close();
}

2 个答案:

答案 0 :(得分:0)

您必须在Access DB中为行插入输入的代码之后使用insert query将其插入DataTable

这是因为DataTable已保存在内存中并且是Disconnected Architecture(表示它从数据库中提取数据并且不再与其连接)。

答案 1 :(得分:0)

您必须重新打开连接并插入该数据库。 SQL看起来像这样:

string sql = String.Format("INSERT INTO Students(FirstName,LastName) VALUES({0},{1})", "John", "Connor")