0

我在尝试将数据插入 SQL Server 数据库时遇到问题。

这是功能

 Public Sub Processsales()

        Dim cust_guid As Guid = Session("guid")
        Dim Iden As Guid = System.Guid.NewGuid
        Dim ssql As String
        ssql = "Insert into WebSite.wTranH ([WebTranHGUID],[TranType],[LOCTN]) values ([Iden],[2],[5])"

        Using connection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("SqlConnectionString"))
            Dim command As New SqlCommand(ssql, connection)
            connection.Open()
            command.ExecuteNonQuery()
        End Using
    End Sub

但它给出了这些错误

列名“Iden”无效。

列名“2”无效。

列名“5”无效。

有什么解决办法吗?

谢谢

4

3 回答 3

2

The best approach would be to use a parametrized query to avoid SQL injection attacks:

Public Sub Processsales()
    Dim cust_guid As Guid = Session("guid")
    Dim Iden As Guid = System.Guid.NewGuid()

    ' define your SQL query and use parameters for the values to be inserted           
    Dim sqlQuery As String = "INSERT INTO WebSite.wTranH([WebTranHGUID], [TranType], [LOCTN]) VALUES (@HGuid, @TranType, @LocTn)"

    Dim connString As String = ConfigurationSettings.AppSettings("SqlConnectionString")

    Using connection As New SqlConnection(connString)
        Using command As New SqlCommand(sqlQuery, connection)
            connection.Open()

            ' add paramters and their values to the SqlCommand instance
            command.Parameters.AddWithValue("@HGuid", Iden)
            command.Parameters.AddWithValue("@TranType", 2)
            command.Parameters.AddWithValue("@LocTn", 5)

            command.ExecuteNonQuery()
            connection.Close()
        End Using
    End Using
End Sub
于 2013-01-27T08:27:08.360 回答
0

你应该使用:

values ('Iden',2 ,5 ) 

反而。

于 2013-01-27T07:58:27.177 回答
0

您的 sql 字符串中有两个错误。您为和列
传递固定值,但列应该获取结构的值而不是其名称。当然,值应该不带括号传递,以免与列名混淆。 您应该更改您的代码,以这种方式将 Iden 的值连接到 sql 命令:TranTypeLOCTNWebTranHGUIDIden

Public Sub Processsales()

    Dim cust_guid As Guid = Session("guid")
    Dim Iden As Guid = System.Guid.NewGuid
    Dim ssql As String
    ssql = "Insert into WebSite.wTranH ([WebTranHGUID],[TranType],[LOCTN]) " + 
    "values (" + Iden.ToString + ",2,5)"

    Using connection As New SqlConnection(....))
        Dim command As New SqlCommand(ssql, connection)
        connection.Open()
        command.ExecuteNonQuery()
    End Using




End Sub
于 2013-01-27T08:11:47.433 回答