【问题标题】:I cannot save new row into Microsoft Access Database via Visual Basic我无法通过 Visual Basic 将新行保存到 Microsoft Access 数据库中
【发布时间】:2020-07-21 05:48:51
【问题描述】:

此代码在我的程序中的其他地方工作,但在这种形式下它不再工作。我有错误

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”。其他人可以找到解决此错误的方法吗?

【问题讨论】:

标签: vb.net visual-studio ms-access


【解决方案1】:

这通常是因为您的列名之一是保留字或包含空格或其他一些特殊字符。当您使用命令生成器时,它只是将列名原样复制到操作命令中。两个主要选项如下:

  1. 不要在SELECT 语句中使用通配符。完整地写出列列表,然后您需要转义任何无效的列名,命令生成器将效仿。
  2. 设置命令生成器的QuotePrefixQuoteSuffix 属性,以便它将所有列名包装在这些字符中,从而转义需要它的那些。对于 Access,值将分别为 "[""]"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2015-06-20
    • 2015-04-12
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多