0

我查看了 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

感谢您提供的任何建议。

4

3 回答 3

1

更改您的代码来执行此操作,这将避免任何 sql 注入,并且您不必处理连接和在值周围添加引号。

在您的表中pricemoney数据类型,Stockint您通过在它们周围添加单引号将值作为字符串发送。

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()
于 2013-02-13T23:04:13.077 回答
0

您将字符串参数 (txtPrice.Text) 作为数字传入(db 列 Price 是一个数字)。您需要先将字符串转换为数字。

于 2013-02-13T22:45:12.997 回答
-1

您应该使用&运算符而不是+运算符来连接字符串

sqlCommand = New SqlCommand("INSERT INTO tblItem(ItemName, Description, 
        Price, Stock) values('" & iName & "','" & iDescription & "','" + iPrice & 
        "','" & iQuantity & "')")
于 2013-02-13T22:51:26.590 回答