此代码可在我程序的其他位置使用,但以这种形式不再起作用。我出现了错误
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
此错误在此时发生
da.Update(ds, "EmployeeTable")
其余代码在下面
Imports System.Data.OleDb
'Allows an connection of a type of Database to VB
Public Class frmAdmin
ReadOnly dbConnection As New OleDb.OleDbConnection
'Declares a variable that will handle the connection to Visual Basic
ReadOnly ds As New DataSet
'Declares the variable that will handle the datasets from the record
Dim da As OleDb.OleDbDataAdapter
'This declares the variable that will handle the data adapted that connects to the Database to VB
Dim sql As String
'A string that will handle SQL which tells the location of data
Private Sub BtnNewEmp_Click(sender As Object, e As EventArgs) Handles btnNewEmp.Click
Dim strProvider As String
Dim strSource As String
Dim strConnString As String
strProvider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
strSource = "../FuelAgencyDataBase.accdb"
strConnString = strProvider & strSource
dbConnection.ConnectionString = strConnString
dbConnection.Open()
sql = "SELECT * FROM EmployeeTable"
da = New OleDbDataAdapter(sql, dbConnection)
da.Fill(ds, "EmployeeTable")
dbConnection.Close()
For Each row In ds.Tables("EmployeeTable").Rows
Dim Test As String = (row.item(1)) & " " + (row.item(2)) & " - " & (row.item(6))
lbxHours.Items.Add(Test)
Next
Dim cb As New OleDbCommandBuilder(da)
'Variable handles how Visual Studio connects to the database
Dim dsNewRow As DataRow
'Variable handles how new rows are added to the record
dsNewRow = ds.Tables("EmployeeTable").NewRow()
dsNewRow.Item(1) = StrFirstName + " " + StrLastName
dsNewRow.Item(2) = StrUsername
dsNewRow.Item(3) = StrPassword
dsNewRow.Item(4) = StrProfession
ds.Tables("EmployeeTable").Rows.Add(dsNewRow)
da.Update(ds, "EmployeeTable")
MsgBox("Employee has been added into the database")
End Sub
我已与数据库建立实时连接,因为其他代码已连接到数据库。该表名称称为“ EmployeeTable”。有人可以找到解决此错误的方法吗?
答案 0 :(得分:1)
通常会发生这种情况,因为您的列名之一是保留字或包含空格或其他一些特殊字符。使用命令构建器时,它只是将列名照原样复制到操作命令中。两个主要选项如下:
SELECT
语句中使用通配符。完整写出列列表,然后您将需要转义任何无效的列名,命令构建器将紧随其后。QuotePrefix
和QuoteSuffix
属性,以使其将所有列名称都包装在这些字符中,从而转义需要它的字符。对于Access,值分别为"["
和"]"
。