从vb.net将数据插入SQL Server

时间:2013-01-27 07:56:05

标签: .net sql sql-server 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”无效。

任何解决方案?

由于

3 个答案:

答案 0 :(得分:2)

最佳方法将是use a parametrized query to avoid SQL injection次攻击:

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

答案 1 :(得分:0)

您应该使用:

values ('Iden',2 ,5 ) 

代替。

答案 2 :(得分:0)

你的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