Syntax error in INSERT INTO Statement when writing to Access

…衆ロ難τιáo~ 提交于 2019-12-02 19:41:01

问题


I am trying to write a program where I can write data to an Access DB but I keep getting the error “Syntax error in INSERT INTO statement”.

FirstLast is the name of the table; First and Last are columns in it.

Imports System.Data.OleDb

Public Class Form1
    Dim theConnectionString As New OleDbConnection
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        theConnectionString.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\user\Documents\Database1.accdb"

        Dim cmd As OleDbCommand = New OleDbCommand("INSERT INTO FirstLast (First, Last) VALUES (@First, TextBox1.text)", theConnectionString)

        cmd.Parameters.Add("@First", OleDbType.Char, 255).Value = TextBox1.Text
        cmd.Parameters.Add("@Last", OleDbType.Char, 255).Value = TextBox1.Text

        Try
            theConnectionString.Open()
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            Throw ex
        Finally
            theConnectionString.Close()
        End Try

    End Sub
End Class

回答1:


I suspect you just need to use named parameters instead of positional ones:

INSERT INTO FirstLast (First, Last) VALUES (@First, @Last)

Note that you should also use Using statements for the connection and command, so that you clean up after yourself automatically without needing an explicit Finally block. (You can get rid of your entire Try/Catch/Finally given that you're just rethrowing the exception anyway.)

As noted in the comment below, you also probably meant to use TextBox2.Text for the @Last parameter, rather than using TextBox1.Text again.



来源:https://stackoverflow.com/questions/16726464/syntax-error-in-insert-into-statement-when-writing-to-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!