VB.NET错误向数据库添加记录

时间:2012-01-19 10:20:32

标签: vb.net record

我正在使用http://homeandlearn.co.uk/NET/nets12p9.html中的代码将记录添加到数据库中。 它说当使用命令构建器时我不应该收到错误消息:

在使用新行传递DataRow集合时,更新需要有效的InsertCommand。

然而,当我进行更新时,我仍然收到错误消息。我该如何解决这个问题?

这是我的代码:

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

2 个答案:

答案 0 :(得分: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")

警告:我假设您正在使用OleDb.OleDbType.VarChar作为Field1和Field2;如果不是,你必须用正确的DB数据格式替换它。

答案 1 :(得分:0)

根据我的阅读here,似乎CommandBuilder应该根据INSERT为您自动生成SELECT命令。

我认为您过早地创建了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()