2011-05-05 54 views
0

我知道這是一個愚蠢的問題,我覺得愚蠢,但我找不到合適的(簡單)的方式來完成我的任務。
我在Visual Studio 2010中導入了一個用於C#項目的Access數據庫:VS爲我創建了(感謝!!)有關我的數據庫的強類型數據集。做得好。
然後,在我的應用程序中,我創建了此數據集的一個新實例CDS ds = new CDS();並在其表中添加記錄。最後我做了ds.AcceptChanges();,但在db上沒有任何反應。
OK,我一派araound和思考(實現?!?)我得打開一個數據庫連接,創建一個DataAdapter和填充我的數據集與此:強類型數據集:添加數據後如何在數據庫上保存數據?

CDS ds = new CDS(); 
OleDbConnection conn = new OleDbConnection(path_to_db); 
conn.Open(); 
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM mytable", conn); 
da.Fill(ds.Editori); //Editori is a TableTable created automatically 
// Insert rows in dataset 
if (ds.HasChanges()) ds.AcceptChanges(); 
int ret = da.Update(ds.Editori); 
Debug.Print("Update() returns: {0}", ret); 
conn.Close(); 

而RET = 0,沒有任何反應數據庫,而在DS.Editori我有106行!

爲了完成我的絕望:表mytable有一個自動增量字段作爲主鍵;當我用da加載ds時,這個字段對每個記錄都是正確的,但是當我在ds上插入行時,記錄有-1,-2,-3等等。爲什麼?

有人能告訴我使用強類型數據集的正確方法嗎? 我要去學習,看書,我答應了,但現在我要遲到了這份工作... 感謝

UPDATE:
作爲從開發-Express的建議我創建了插入命令,但結果是一樣的:當我更新da時,db上沒有任何反應。

OleDbCommand cmd = new OleDbCommand(
    "INSERT INTO Editori (ID,Editore) VALUES(?,?)", conn); 
cmd.Parameters.Add("@ID", OleDbType.Integer); 
cmd.Parameters.Add("@Editore", OleDbType.VarChar, 255, "Editore"); 
da.InsertCommand = cmd; 
int ret = da.Update(ds.Editori); 
Debug.Print("Update() returns: {0}", ret); 
conn.Close(); 

另一個更新: 我解決了主鍵的問題:在生成的類我手動不得不改變所有這些行:

this.columnID.AutoIncrementSeed = 1; // It was -1 
this.columnID.AutoIncrementStep = 1; // It was -1 

回答

0

你還應該指定OleDbDataAdapter的的更新命令和然後通過調用da.Update方法來執行它。還有就是如何能在MSDN工作的一個示例:

OleDbDataAdapter.OleDbDataAdapter(String, OleDbConnection) Constructor

+0

我已經想過這個,但是......爲什麼不VS不是自動創建它?我會試着讓你知道。謝謝 – Marco 2011-05-05 16:12:21

+0

我試着用insert命令,但它不起作用。我很傷心...... – Marco 2011-05-05 16:29:03

+0

您可以使用OleDbCommandBuilder類自動生成基於您的SelectCommand的INSERT/UPDATE/DELETE語句。 – Patrick 2011-05-05 17:16:18

1

,如果您使用Visual Studio設計一個強類型DataSet中,會有數據集中的一個TableAdapters或TableManager爲該數據集創建。

MSDN給出了使用下面的例子:

NorthwindDataSet northwindDataSet = new NorthwindDataSet(); 

NorthwindDataSetTableAdapters.CustomersTableAdapter customersTableAdapter = 
    new NorthwindDataSetTableAdapters.CustomersTableAdapter(); 
//Fill from database 
customersTableAdapter.Fill(northwindDataSet.Customers); 
//... changes to table 
//Save changes to database 
customersTableAdapter.Update(northwindDataSet.Customers); 

另外,如果您的Visual Studio設計創建了一個TableManager:

NorthwindDataSet northwindDataSet = new NorthwindDataSet(); 
TableAdapterManager northwindTableManager = new TableAdapterManager(); 

//Fill from database 
northwindTableManager.CustomersTableAdapter.Fill(northwindDataSet.Customers); 
//... changes to table 
//Save changes to database 
northwindTableManager.CustomersTableAdapter.Update(northwindDataSet.Customers);