我查看了StackOverflow以及其他一些网站,我发现了一些代码将它们组合在一起:
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim sqlConnection As SqlConnection
Dim sqlCommand As SqlCommand
Dim sqlString, iName, iDescription As String
Dim iQuantity As Integer
Dim iPrice As Decimal
Protected Sub cmdAddStock_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles cmdAddStock.Click
iName = txtItemName.Text
iDescription = txtDescription.Text
iQuantity = txtQuantity.Text
iPrice = txtPrice.Text
Using myConnection As New SqlConnection("Server=localhost;Database=BBBLeeds;
Trusted_Connection=True")
myConnection.Open()
sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
Price, Stock) values('" + iName + "','" + iDescription + "','" + iPrice +
"','" + iQuantity + "')")
sqlCommand.ExecuteNonQuery()
myConnection.Close()
Response.Redirect(Request.RawUrl, True)
End Using
End Sub
End Class
返回的错误如下:
“从字符串转换”INSERT INTO tblItem(ItemName,De“到'Double'类型无效。”
这是SQL的数据结构:
http://i23.photobucket.com/albums/b368/Damo115/Untitled.png
感谢您提供任何建议。
答案 0 :(得分:1)
更改代码以执行此操作,这将避免任何sql注入,并且您不必处理连接并在值周围添加引号。
在您的表格price
中,money
数据类型为Stock
,int
为sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
Price, Stock) values(@item,@descr,@price,@stock)")
sqlCommand.Parameters.AddWithValue("@item",iName)
sqlCommand.Parameters.AddWithValue("@descr",iDescription)
sqlCommand.Parameters.AddWithValue("@price",iPrice)
sqlCommand.Parameters.AddWithValue("@stock",iQuantity)
sqlCommand.ExecuteNonQuery()
,但您通过在其周围添加单引号将值作为字符串发送。
{{1}}
答案 1 :(得分:0)
将字符串参数(txtPrice.Text)作为数字传递(db列Price是一个数字)。您需要先将字符串转换为数字。
答案 2 :(得分:-1)
您应该使用&
运算符而不是+
运算符来连接字符串
sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description,
Price, Stock) values('" & iName & "','" & iDescription & "','" + iPrice &
"','" & iQuantity & "')")