2014-01-08 151 views
1

如何將DataTable保存到文件中。 accdb(Access)現有的一個?我用下面的代碼,它不工作:C#DataTable更新訪問數據庫

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(); 
} 

變量數據表上初始化文件的原始內容,然後將其修改通過添加行,我現在有更新的表數據庫。

我嘗試使用下面的代碼,但是,這並不工作:(

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

)'的'觀看Window',你得到什麼變化? –

+0

這種方法對另一個功能很有用,但不適用於此。謝謝 – user3105160

回答

4

假設你已經在數據表中的一些變化,那麼你可以通過生成的更新/插入/刪除命令到適配器以這種方式

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

適配器現在知道如何如果發出`dataTable.GetChanges(更新表格

+0

很好,史蒂夫,我錯過了當我讀取'GetDeleteCommand()'行時OP沒有分配命令的事實! –

+0

對不起,但這不起作用:/ – user3105160

+0

什麼不起作用?任何錯誤消息或? – Steve