当我尝试将项目插入数据库时​​,它说“,”附近的语法不正确?

It says Incorrect syntax near ',' when I try to insert an item into my database?

代码:

Private m_cn As New SqlConnection
Private m_DA As SqlDataAdapter
Private m_CB As SqlCommandBuilder
Private m_DataTable As New DataTable
Private m_intRowPosition As Integer = 0

Private Sub InsertDatabaseItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    m_cn.ConnectionString = "Data Source=My-PC\SQLSERVEREXPRESS;Initial Catalog=ConvienienceProducts;Integrated Security=True"

    m_cn.Open()
    m_DA = New SqlDataAdapter("Select * From ProductIndex", m_cn)
    m_CB = New SqlCommandBuilder(m_DA)
End Sub

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
                              txtID.Text & "," &
                              txtName.Text & "," &
                              txtPrice.Text & "," &
                              txtDesc.Text & ")"), m_cn)

    cmd.ExecuteNonQuery()

    MsgBox("Success....", MsgBoxStyle.Information, "SUCCESS")

    Me.Hide()

    txtID.Clear()
    txtName.Clear()
    txtPrice.Clear()
    txtDesc.Clear()

    m_cn.Close()
    m_cn.Dispose()
End Sub

Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
    Me.Hide()
End Sub

这是错误信息:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Incorrect syntax near ','.

您需要将字符串值用单引号括起来

Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES('" & txtID.Text & "',

很难看到,但是在变量周围的双引号前后有一个单引号。

我已经回答了你的具体问题,但你应该使用参数

您的代码应该使用 parameters。试试这个:

Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
                          "@ID," &
                          "@Name," &
                          "@Price," &
                          "@Desc)"), m_cn)

cmd.Parameters.Add("@ID", SqlDbType.Char)
cmd.Parameters("@ID").Value = txtID.Text
cmd.Parameters.Add("@Name", SqlDbType.Char)
cmd.Parameters("@Name").Value = txtName.Text   
cmd.Parameters.Add("@Price",  SqlDbType.Char)
cmd.Parameters("@Price").Value = txtPrice.Text
cmd.Parameters.Add("@Desc",  SqlDbType.Char)
cmd.Parameters("@Desc").Value = txtDesc.Text

类型可能有误(尤其是 Price,可能 ID),但是你知道它们是什么,而我不知道,你可以轻松地更正它们。