我是Microsoft Access的新手。我需要编写VB代码来在按钮事件单击时执行数据库插入。插入应从按钮所在的表单中获取信息。 我知道您可以通过以下方式获取表单信息:
Form![tablename]![columnname]
但是如何将该信息插入到另一个表中呢?我看到了这篇文章How to insert data into a Microsoft Access Database?,但我认为它仅适用于.NET,因为我无法找到Access参考页面http://msdn.microsoft.com/en-us/library/office/aa296940(v=office.11).aspx上列出的OleDbConnection对象
答案 0 :(得分:4)
你说VB,但我认为你在谈论VBA(Access使用的VB)。
如果您要插入的表与您提供命令的表位于同一数据库中,则不需要连接。它是内置的。执行查询的命令是CurrentDB.Execute {SQL statement}
所以,你有一些看起来像这样的东西:
Dim strSQL as String
strSQL = "INSERT INTO TableName( FieldName)
strSQL = strSQL & "SELECT 'MyData'"
CurrentDB.Execute strSQL
答案 1 :(得分:4)
Private Sub btnAdd_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理btnAdd.Click Dim sql As String
Dim con As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
con.ConnectionString = "PROVIDER = Microsoft.Jet.OLEDB.4.0; Data Source = E:\test.mdb"
con.Open()
sql = "INSERT INTO student(name, Address) VALUES('" & Me.txtName.Text & "','" & Me.txtAddress.Text & "')"
cmd = New OleDb.OleDbCommand(sql, con)
cmd.ExecuteNonQuery()
MsgBox("saved")
txtName.Text = ""
txtAddress.Text = ""
con.Close()
答案 2 :(得分:0)
Dim con As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
con.ConnectionString = "PROVIDER = Microsoft.Jet.OLEDB.4.0; Data Source = E:\test.mdb"
con.Open()
sql = "INSERT INTO student(name, Address) VALUES('" & Me.txtName.Text & "','" & Me.txtAddress.Text & "')"
cmd = New OleDb.OleDbCommand(sql, con)
cmd.ExecuteNonQuery()
MsgBox("saved")
txtName.Text = ""
txtAddress.Text = ""
con.Close()