【问题标题】:It says Incorrect syntax near ',' when I try to insert an item into my database?当我尝试将项目插入数据库时​​,它显示“,”附近的语法不正确?
【发布时间】:2016-06-12 22:31:46
【问题描述】:

代码:

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

这是错误信息:

System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常

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

【问题讨论】:

  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入

标签: sql vb.net visual-studio-2015 sql-server-express


【解决方案1】:

您的代码应该使用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),但你知道它们是什么,而我不知道,你可以很容易地纠正它们。

【讨论】:

    【解决方案2】:

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

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

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

    我已经回答了您的特定问题,但您应该使用参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2019-05-26
      • 2020-06-17
      相关资源
      最近更新 更多