我可以从Access数据库中选择数据,但我尝试了很多方法来INSERT INTO数据库。没有错误消息,但它没有插入数据。
代码:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
我只想要一种简单易用的方法来插入Access数据库。是否可能因为Access数据库的问题?我可以通过直接在Access中运行查询来插入此查询。
答案 0 :(得分:0)
首先,我会检查数据库设置。如果您的应用程序每次运行时都会复制数据库的新副本,这将解释为什么您可以选择现有数据以及未保存新数据的原因(好吧它正在保存,但数据库不断被旧数据替换) )。而是将其设置为COPY IF NEWER。
此外,您应该始终使用参数化查询来保护您的数据。它比字符串连接命令更容易出错,并且更容易调试。
此外,我建议使用USING块来处理数据库连接,以便您的代码自动处理不再需要的资源,以防您在完成后忘记处理连接。这是一个例子:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(@code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("@code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
答案 1 :(得分:0)
这是一个示例,其中数据操作与表单代码分开。
从表单中调用
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
后端类,其中为AddNewRow的最后一个参数设置新主键,如果AddNewRow返回true,则可以使用该主键。
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (@CompanyName, @ContactName)"
cmd.Parameters.AddWithValue("@CompanyName", CompanyName)
cmd.Parameters.AddWithValue("@ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select @@Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class