2011-07-13 27 views
0

我遇到了通過使用DataAdapter回寫到Access數據庫(.accdb)的問題。向DataSet中添加一個新項目,將其寫入Access DB

目前,我有一個填充方法,用數據填充DataSet表。這段代碼目前位於我的Form_Load()中。

// TODO: This line of code loads data into the 'hCAliasDataSet.Topics' table. You can move, or remove it, as needed. 
this.topicsTableAdapter.Fill(this.hCAliasDataSet.Topics); 

然後,我有一個cmdAdd_Click()事件,這顯然是添加一個新行,在hCAliasDataSet內坐在Topcis表。

// Create a new row, append it to Topics table. 
DataRow DR; 
DR = this.hCAliasDataSet.Tables["Topics"].NewRow(); 
this.hCAliasDataSet.Tables["Topics"].Rows.Add(DR); 

接下來,我創建了一些代碼來caputre的列值的一個輸入。

 // Capture user input 
     sTopicName = Interaction.InputBox("Please Enter Topic Name", "Topic Name", null, 100, 100); 
     // Set the Topic value for the new Row 
     DR["Topic"] = sTopicName; 

我的問題,我假設在這裏,我調用dataAdapter來更新主題表。我手動檢查數據庫,並且沒有創建任何新行?

// Commit the changes back to the hCAlias DataBase (hcalias.accdb). 
this.topicsTableAdapter.Update(this.hCAliasDataSet.Topics); 

編輯:我相信我需要創建一個INSERT查詢,我的TableAdapter,這會是正確的嗎?

+0

你可以看到這個博客。 http://www.cnblogs.com/chenping-987123/archive/2010/08/04/1792149.html – yapingchen

回答

1

適配器應該在幕後爲您自動生成插入語句。 您的代碼看起來不錯,但是您可能會對其中一個列有一個限制,使其無法保存。 (就像您沒有指定任何數據的非空列)。但是,如果有一個取消插入的約束,通常會得到一個異常。

您可以嘗試這些替代方案之一,但他們基本上是相同的事情:

this.topicsTableAdapter.Update(this.hCAliasDataSet); this.topicsTableAdapter.Update(DR); this.topicsTableAdapter.Insert(sTopicName); //添加任何其他列在這裏

+0

謝謝德文。插入完成了這項工作。我發現的其他一些事情我也必須在DataSet上將「強制約束」屬性更改爲True。 –

1

你應該調用在數據集中的AcceptChanges:

hCAliasDataSet.AcceptChanges(); 

,然後提交給你的TableAdapter數據庫。

+0

感謝您的輸入,我已經調用了AcceptChanges()。不幸的是,它不適合我。 –

1

Update()方法只是更新現有記錄,您需要使用TableAdapter的Insert()方法添加一個新行。 VC#將爲您創建一個默認的Insert()方法(可能會超載)...但是會有一種方法可以讓您明確插入值...

例如...

this.topicsTableAdapter.Insert(INT列1,串列2等等等等)

這將在數據庫中創建一個新的行,並與您指定的值來填充它。

+0

感謝Chris,在接受了Devin的回覆之後,我查看了VS爲我創建的Insert語句。 –

相關問題