繁体   English   中英

从vb.net将数据插入SQL Server

[英]inserting data into SQL Server from vb.net

我在尝试将数据插入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”无效。

有解决方案吗

谢谢

最好的方法使用参数化查询来避免SQL注入攻击:

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

你应该使用:

values ('Iden',2 ,5 ) 

代替。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM