How do I add a record to an Access database using VB?
To add records to an Access database, make sure you are already connected to the database. Create a connection using the OleDbConnection object provided by the ADO.NET library and open the connection.
Next, create an INSERT INTO statement to insert new records into the table. Specify the table name, the fields to be inserted, and their corresponding values.
Finally, execute the INSERT statement using the OleDbCommand object and then close the connection.
Here is an example code:
Imports System.Data.OleDb
Public Sub AddRecordToAccessDatabase()
' 连接字符串
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path\to\database.accdb"
' 创建连接对象
Using connection As New OleDbConnection(connectionString)
' 打开连接
connection.Open()
' 创建INSERT语句
Dim insertQuery As String = "INSERT INTO TableName (Field1, Field2) VALUES (@Value1, @Value2)"
' 创建命令对象
Using command As New OleDbCommand(insertQuery, connection)
' 设置参数值
command.Parameters.AddWithValue("@Value1", "Value1")
command.Parameters.AddWithValue("@Value2", "Value2")
' 执行INSERT语句
command.ExecuteNonQuery()
End Using
' 关闭连接
connection.Close()
End Using
End Sub
In this example, replace “TableName” with the name of the table where records will be inserted, “Field1” and “Field2” with the corresponding fields in the table, and “@Value1” and “@Value2” as parameter names that can be customized along with their values as needed.
Replace the connection string in the code with the actual database path and name.
Make sure to reference the System.Data.OleDb namespace in the code to use the OleDbConnection and OleDbCommand classes.