[英]VB.NET Insert Data into MS Access DB
This is my first attempt at working with .NET and a database. 这是我第一次尝试使用.NET和数据库。
I am trying to add records to a table but nothing is being added. 我正在尝试将记录添加到表中,但是什么也没有添加。 I have stripped it down to just the basic code below. 我将其简化为下面的基本代码。
No errors are generated but nothing is added to the table. 没有错误生成,但没有任何内容添加到表中。
Imports System.Data
'Imports System.Data.OleDb
Class Form1
Dim dbProvider As String
Dim dbSource As String
Dim dbPathAndFilename As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" ' MDB
'dbProvider = "PROVIDER=Microsoft.Ace.OLEDB.12.0;" 'ACCDB
dbSource = "Data Source="
LoadData()
End Sub
Sub LoadData()
'Connect to db
'You could store the db path in the Settings of the App.
'dbPathAndFilename = My.Settings.dbPath
dbPathAndFilename = "C:\temp\VB\DBTest\Test.mdb"
con.ConnectionString = dbProvider & dbSource & dbPathAndFilename
con.Open()
sql = "INSERT INTO Table1(Field1) VALUES('Field1');"
da = New OleDb.OleDbDataAdapter(sql, con)
con.Close()
End Sub
End Class
Try this 尝试这个
Class Form1
Private dbProvider As String
Private dbPathAndFilename As String
Sub LoadData()
dbProvider = "Microsoft.Jet.OLEDB.4.0;"
dbPathAndFilename = "C:\temp\VB\DBTest\Test.mdb"
Using con As New OleDb.OleDbConnection($"PROVIDER={dbProvider};DATA SOURCE={dbPathAndFilename}")
con.Open()
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO Table1([Field1]) VALUES(@field1);"
cmd.Parameters.AddWithValue("@field1", field1Value) ' replace field1Value with your value
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
End Class
It has a few advantages over your version. 与您的版本相比,它具有一些优势。
Using
blocks 它通过Using
块限制了一次性物品的范围 Imports System.Data
Imports System.Data.OleDb
Class Form1
Dim dbProvider As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" ' MDB
Dim dbSource As String = "Data Source="
Dim dbPathAndFilename As String
Public Property ConnectionString as String
Get
return $"{dbProvider}{dbSource}{dbPathAndFilename}"
End Get
End Property
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbPathAndFilename = "C:\temp\VB\DBTest\Test.mdb"
LoadData()
End Sub
Sub LoadData()
Dim sql As String = "INSERT INTO Table1(Field1) VALUES(?);"
Using con As New OleDbConnection(ConnectionString), _
cmd As New OleDbCommand(sql)
cmd.Parameters.Add("Field1", OleDbType.VarWString, 50).Value = "Field1"
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
End Class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.