我正在尝试在 MS Access 中插入数据,但是当我尝试打开数据库时,数据不存在。我是使用 vb.net 和数据库的初学者
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim con As New OleDbConnection
Try
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Desktop\School\DBLC.accdb"
con.Open()
Dim query As String
query = "INSERT INTO LC ([Name of Applicant], [Address of Applicant], [Contact of Applicant]) VALUES (@NameApp, @AddressApp, @ContactApp)"
Dim command As OleDbCommand = New OleDbCommand(query, con)
command.Parameters.AddWithValue("@NameApp", txtboxNameApp.Text)
command.Parameters.AddWithValue("@AddressApp", txtboxAddressApp.Text)
command.Parameters.AddWithValue("@ContactApp", txtboxContactApp.Text)
MsgBox("New record added!")
Catch ex As Exception
MsgBox(Convert.ToString(ex))
Finally
con.Close()
End Try
End Sub
您的代码设置了 SQL,您的代码设置了参数,但随后不执行您创建的命令。你也没有
因此,这段代码应该可以工作:
Dim strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Desktop\School\DBLC.accdb"
Dim query As String
query = "INSERT INTO LC ([Name of Applicant], [Address of Applicant], [Contact of Applicant])
VALUES (@NameApp, @AddressApp, @ContactApp)"
Using conn As New OleDbConnection(strCon)
conn.Open()
Using command As New OleDbCommand(query, conn)
command.Parameters.Add("@NameApp", OleDbType.VarWChar).Value = txtboxNameApp.Text
command.Parameters.Add("@AddressApp", OleDbType.VarWChar).Value = txtboxAddressApp.Text)
command.Parameters.Add("@ContactApp", OleDbType.VarWChar).Value = txtboxContactApp.Text)
command.ExecuteNonQuery()
End Using
End Using
MsgBox("New record added!")
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
因此,您缺少创建的命令对象的“执行”。
请注意上面我们如何在 using 语句中扭曲连接和命令对象,因为这确保所有内容都被清理、处理,并且连接自动关闭。