代码:
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 ','.
请您参考如下方法:
您的代码应该使用 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
),但是你知道它们是什么,而我不知道,你可以很容易地纠正它们.