当我尝试将项目插入数据库时​​,它会在','附近说错误的语法?

use*_*383 2 sql vb.net sql-server-express visual-studio-2015

代码:

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
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

System.Data.dll中发生了类型为"System.Data.SqlClient.SqlException"的未处理异常

附加信息:','附近的语法不正确.

Ala*_*own 6

您的代码应该正在使用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
Run Code Online (Sandbox Code Playgroud)

这些类型可能是错误的(特别是Price,可能ID),但是当你知道它们是什么时,我却不知道,你可以很容易地纠正它们.