2012-01-19 74 views
0

我正在使用http://homeandlearn.co.uk/NET/nets12p9.html的代碼添加記錄到數據庫。 它使用命令生成器時說,我不應該得到錯誤消息:VB.NET錯誤添加記錄到數據庫

更新需要一個有效的InsertCommand與新行傳遞DataRow集合時。

但是,當我做更新時,我仍然收到錯誤消息。我怎樣才能解決這個問題?

這是我的代碼:

Dim dbProv As String 
Dim dbSource As String 
Dim con As New OleDb.OleDbConnection 
Dim ds As New DataSet 
Dim da As New OleDb.OleDbDataAdapter 
Dim sql As String 
Dim Command As OleDb.OleDbCommand 
Dim dr As DataRow 
Dim cb As New OleDb.OleDbCommandBuilder(da) 

sql = "SELECT * FROM Cliënten" 
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" 
dbSource = "Data Source = [mydatabase]" 
con.ConnectionString = dbProv & dbSource 
con.Open() 
da = New OleDb.OleDbDataAdapter(sql, con) 
da.Fill(ds, "Cliënten") 

dr = ds.Tables("Cliënten").NewRow() 
dr.Item("Field1") = TextBox1.Text 
dr.Item("Field2") = TextBox2.Text 
ds.Tables("Cliënten").Rows.Add(dr) 

da.Update(ds, "Cliënten") 
MsgBox("New Record added to the Database") 

con.Close() 

回答

0

爲了da.Update()的作品,你必須指定一個有效的InsertCommand,那麼DataAdapter的會自動執行它。下面一個例子:

da.InsertCommand = New OleDb.OleDbCommand("INTERT INTO Cliënten (Field1, Field2) VALUES (@field1, @field2)") 
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("@field1", OleDb.OleDbType.VarChar, 0, "Field1")) 
da.InsertCommand.Parameters.Add(New OleDb.OleDbParameter("@field2", OleDb.OleDbType.VarChar, 0, "Field2")) 
da.Update(ds, "Cliënten") 

警告:我假設你正在使用的字段1和字段2 OleDb.OleDbType.VarChar;如果不是,則必須將其替換爲正確的DB數據格式。

+1

我覺得CommandBuilder的類應該根據SELECT自動生成INSERT ... –

0

從我讀的here看起來好像CommandBuilder應該根據SELECT自動生成INSERT命令。

我想你創建CommandBuilder對象太早 - 即你指定SELECT命令/初始化連接等

這或許可以更好地工作之前...

Dim dbProv As String 
Dim dbSource As String 
Dim con As New OleDb.OleDbConnection 
Dim ds As New DataSet 
Dim da As New OleDb.OleDbDataAdapter 
Dim sql As String 
Dim Command As OleDb.OleDbCommand 
Dim dr As DataRow 

sql = "SELECT * FROM Cliënten"    'Consider specifying columns 
              'individually rather than using * 
dbProv = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" 
dbSource = "Data Source = [mydatabase]" 
con.ConnectionString = dbProv & dbSource 
con.Open() 
da = New OleDb.OleDbDataAdapter(sql, con) 

Dim cb As New OleDb.OleDbCommandBuilder(da) 'Init CommandBuilder here 
cb.RefreshSchema()       'This may also help 

da.Fill(ds, "Cliënten") 
dr = ds.Tables("Cliënten").NewRow() 
dr.Item("Field1") = TextBox1.Text 
dr.Item("Field2") = TextBox2.Text 
ds.Tables("Cliënten").Rows.Add(dr) 

da.Update(ds, "Cliënten") 
MsgBox("New Record added to the Database") 

con.Close() 
相關問題