参数化INSERT INTO语句

时间:2016-02-25 05:02:22

标签: vb.net

我正在尝试将数据从VB.NET插入到MS Access中,但我在INSERT INTO语句中得到了#34;语法错误。"来自MessageBox.Show(ex.Message)。

有人可以自由查看我的代码并帮我解决问题吗?此外,如果你们有更好的替代编码方式,我将非常感激。提前谢谢。

Imports System.Data.OleDb
Public Class addNew
Dim conn As New OleDbConnection()
Dim sqlCom As New OleDbCommand()

Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
    If txtFirstName.Text = "" Or txtLastName.Text = "" Or txtContact.Text = "" Or txtEmail.Text = "" Or comboMembershipType.Text = "" Then
        MessageBox.Show("Please complete the required fields.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        Try
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Application.StartupPath & "\igcDatabase.accdb"
            sqlCom.Connection = conn
            conn.Open()

            sqlCom.CommandText = "INSERT INTO Members (Member First Name, Member Last Name, Contact Number, E-mail Address)" _
            & " VALUES (@FirstName, @LastName, @Contact, @Email)"

            sqlCom.Parameters.AddWithValue("FirstName", txtFirstName.Text)
            sqlCom.Parameters.AddWithValue("LastName", txtLastName.Text)
            sqlCom.Parameters.AddWithValue("Contact", txtContact.Text)
            sqlCom.Parameters.AddWithValue("Email", txtEmail.Text)

            sqlCom.ExecuteNonQuery()
            MessageBox.Show("Successfully added member!")
            conn.Close()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End If
End Sub
End Class

问题已解决。

2 个答案:

答案 0 :(得分:0)

我认为列名创建问题,请您查一下列名吗?是否输入正确?我认为Member First Name之间不会有空格。我建议你使用Parameters.Add() instead for Parameters.AddWithValue();以下代码将是一个例子:

        sqlCom.Parameters.Add("@FirstName", OleDbType.VarChar).Value = txtFirstName.Text
        sqlCom.Parameters.Add("@LastName",OleDbType.VarChar).Value =  txtLastName.Text
        sqlCom.Parameters.Add("@Contact",OleDbType.VarChar).Value = txtContact.Text
        sqlCom.Parameters.Add("@Email",OleDbType.VarChar).Value =txtEmail.Text

答案 1 :(得分:0)

尝试在[]中包装您的字段名称,例如[会员名字]。

您可能会错误地获取字段的语法。检查异常的其余部分可能有助于揭示语法问题。