我使用此代碼爲我創建了一個我的Access表中的DataTable
。從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();
}
但你不能將我的DataTable直接複製到Access文件中? – user3105160
不完全確定,但我不相信有可能沒有明確重新打開連接。 – njenson
你能幫我或建議一種方法來複制整個dataTable嗎?這很重要。 – user3105160