问题
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