Syntax error when executing INSERT INTO statement

前端 未结 4 1257
灰色年华
灰色年华 2021-01-23 08:52

I input the Right dataSource but it didnt i cant fixed the problem cmd.ExecuteNonQuery() saying:

Syntax error in INSERT INTO

相关标签:
4条回答
  • 2021-01-23 08:58

    It is likely that one of your Me.textN.Text values has an apostrophe in it or some other unexpected character that is breaking your SQL quotes. The solution to this is to use parametized queries and/or stored procedure instead.

    This incidentally, will also protect you form the SQL Injection attacks that take advantage of the same shortcoming in composing SQL commands as strings in the client application.

    (NOTE: I am assuming the Me.text1.Text as the StickerCode is a number. Otherwise that's the problem as you are not quoting it the way you do with the other columns.)

    0 讨论(0)
  • 2021-01-23 08:59

    You are missing single quotes around your first value. Try

    " VALUES('" & Me.text1.Text & "','" & Me.text2.Text & "','" & _
        Me.text3.Text & "','" & Me.text4.Text & "','" & Me.text5.Text & "','" & _
        Me.text6.Text & "','" & Me.text7.Text & "','" & Me.text8.Text & "','" & _
        Me.text9.Text & "','" & Me.text10.Text & "','" & Me.text11.Text & "','" & _
        Me.text12.Text & "')"
    
    0 讨论(0)
  • 2021-01-23 09:00

    First line is missing as '

    ...
    "SET StickerCode='" & Me.text1.Text & "'" & _ 
    ...
    
    0 讨论(0)
  • 2021-01-23 09:05

    Use a parameterized query, like this:

    cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
                            " VALUES(@StickerCode, @Description, @Company, @Department, @Location, @User, @SerialNumber, @DatePurchased, @Tagable, @Quantity, @Brand, @Model)"
    
    cmd.Parameters.AddWithValue("@StickerCode", Me.Text1.Text)
    cmd.Parameters.AddWithValue("@Description", Me.Text2.Text)
    cmd.Parameters.AddWithValue("@Company", Me.Text3.Text)
    cmd.Parameters.AddWithValue("@Department", Me.Text4.Text)
    cmd.Parameters.AddWithValue("@Location", Me.Text5.Text)
    cmd.Parameters.AddWithValue("@User", Me.Text6.Text)
    cmd.Parameters.AddWithValue("@SerialNumber", Me.Text7.Text)
    cmd.Parameters.AddWithValue("@DatePurchased", Me.Text8.Text)
    cmd.Parameters.AddWithValue("@Tagable", Me.Text9.Text)
    cmd.Parameters.AddWithValue("@Quantity", Me.Text10.Text)
    cmd.Parameters.AddWithValue("@Brand", Me.Text11.Text)
    cmd.Parameters.AddWithValue("@Model", Me.Text12.Text)
    

    Note: It is best to keep the order of the parameters in line with the query, as databases like Microsoft Access will not execute the query correctly if the order is altered.

    0 讨论(0)
提交回复
热议问题