Vb.net 我正在尝试添加和更新数据库。代码的添加部分工作正常,但更新时出现错误,显示列名无效
可能错误就在查询的这一部分Vb.net 我正在尝试添加和更新数据库。代码的添加部分工作正常,但更新时出现错误,显示列名无效,vb.net,Vb.net,可能错误就在查询的这一部分 Private Sub Btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnadd.Click Dim cmd As New SqlCommand If Not cnn.State = ConnectionState.Open Then 'open connection if it is not yet open
Private Sub Btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnadd.Click
Dim cmd As New SqlCommand
If Not cnn.State = ConnectionState.Open Then
'open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new or update
If Me.Txtproductname.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO stock(product_name, product_id, unit,price, item_type, date_in) " & _
" VALUES('" & Me.Txtproductname.Text & "','" & Me.Txtproductid.Text & "','" & _
Me.txtunit.Text & "','" & Me.txtprice.Text & "','" & _
Me.Txtitem_type.Text & "','" & Me.txtdate_in.Text & "')"
cmd.ExecuteNonQuery()
Else
'update data in table
cmd.CommandText = "UPDATE stock " & _
" SET product_name=" & Me.Txtproductname.Text & _
", product_id='" & Me.Txtproductid.Text & "'" & _
", unit='" & Me.txtunit.Text & "'" & _
", price='" & Me.txtprice.Text & "'" & _
", item_type='" & Me.Txtitem_type.Text & "'" & _
", date_in='" & Me.txtdate_in.Text & "'" & _
" WHERE product_name=" & Me.Txtproductname.Tag
cmd.ExecuteNonQuery()
End If
'refresh data in list
RefreshData()
'clear form
Me.Btnclear.PerformClick()
'close connection
cnn.Close()
End Sub
它不包含在单一报价中
但我要说的是,这种插入或更新的方式确实是错误的
- 首先,如果您的任何文本字段包含一个单引号,您将得到一个 语法错误
- 其次,将代码暴露于用户编写的任何恶意文本中
例如,这可以用于更新
SET product_name=" & Me.Txtproductname.Text &
通过这种方式,您可以让框架代码处理文本框的正确解析,并防止向数据库传递意外命令的任何可能性
除此之外,我想询问您的数据库字段是否都是字符串类型。有些字段似乎是不同类型的,如中的
date\u和price
如果这些字段不是文本类型,则应添加转换
cmd.CommandText = "UPDATE stock " & _
" SET product_name=@prodName " & _
", product_id=@prodID" & _
", unit=@unit" & _
", price=@price" & _
", item_type=@itemType" & _
", date_in=@date" & _
" WHERE product_name=@prodTag"
cmd.Parameters.AddWithValue("@prodName", Me.Txtproductname.Text)
cmd.Parameters.AddWithValue("@prodID", Me.Txtproductid.Text)
cmd.Parameters.AddWithValue("@unit", Me.txtunit.Text)
cmd.Parameters.AddWithValue("@price", Me.txtprice.Text)
cmd.Parameters.AddWithValue("@itemType", Me.Txtitem_type.Text)
cmd.Parameters.AddWithValue("@date", Me.txtdate_in.Text)
cmd.Parameters.AddWithValue("@prodTag", Me.Txtproductname.Tag)
cmd.ExecuteNonQuery()
在更新中,您忘记了在产品名称
之后的单引号。听起来可能很愚蠢,但它没有指定无效的列名吗
您是否需要在SET和Where子句中对产品名称的值进行单个tic?我不是OP,只是好奇而已。如何更改插入/更新以使其不受注射影响?@PhaDaPhunk:简单,使用。谢谢你,它起作用了……这是我表单上的完整代码,它起作用了。我只是想让你看一看,并帮助我克服任何SQL注入攻击,因为这对我来说是一个新概念:我看不到你的“完整代码”,但在你问题的代码中,同样的更新查询问题也出现在insert语句中。只需检查表示sql命令的每个文本(最常见的是SELECT、INSERT、UPDATE和DELETE)。如果您将用户在中键入的值串联在一起生成此文本,则会遇到麻烦。
cmd.Parameters.AddWithValue("@date", Convert.ToDateTime(Me.txtdate_in.Text))