【问题标题】:inserting data into SQL Server from vb.net从 vb.net 将数据插入 SQL Server
【发布时间】:2013-01-27 07:56:05
【问题描述】:

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

有什么解决办法吗?

谢谢

【问题讨论】:

  • 从值中删除 []。 ssql = "插入到 WebSite.wTranH ([WebTranHGUID],[TranType],[LOCTN]) 值 (Iden,2,5)"

标签: .net sql sql-server vb.net


【解决方案1】:

最佳方法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

【讨论】:

  • @user2008654: WHERE(在哪一行)你得到这个错误了吗?你确实声明了一个变量Iden - 对吧??
【解决方案2】:

你应该使用:

values ('Iden',2 ,5 ) 

改为。

【讨论】:

  • -1。看,'Iden' 显然是一个变量(在字符串前 2 行声明),您尝试在其中插入名称。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多