将参数传递给SQLCommandText

时间:2016-01-14 19:53:38

标签: .net sql-server vb.net

我试图通过VB.NET执行传递参数到SQL INSERT语句:

Using cnn As SqlConnection = New SqlConnection(conn)
                cnn.Open()
                Using insertTrans As SqlTransaction = cnn.BeginTransaction
                    Using cmd As SqlCommand = cnn.CreateCommand()
                        'skip 1st row
                        Dim firstRow As Boolean = True
                        For Each item As String In lines
                            cmd.CommandText = "INSERT INTO [matrixtest].[dbo].[SM_Fatca_GinList] VALUES (@gin, @name, @country)"
                            If Not firstRow Then
                                item = item.Replace(""" ,", """,")
                                item = item.Replace(", """, ",""")
                                item = item.Replace(""",""", """__||__""")
                                item = item.Replace("""", "")
                                fields = item.Split("__||__")
                                If Not String.IsNullOrEmpty(fields(0)) Then
                                    If Not fields(0).Length = 0 Then
                                        cmd.Parameters.AddWithValue("@gin", fields(0))
                                        cmd.Parameters.AddWithValue("@name", fields(1))
                                        cmd.Parameters.AddWithValue("@country", fields(2))
                                    End If
                                End If
                            End If
                            firstRow = False
                            cmd.Transaction = insertTrans
                            cmd.ExecuteNonQuery()
                        Next
                    End Using
                End Using
            End Using

我收到此错误:Must declare the scalar variable "@gin".

这看起来像是一个SQL错误,但为什么我必须在SQL中声明变量?我只是使用这种语法来传递参数?我做错了什么,如何解决?

2 个答案:

答案 0 :(得分:1)

由于仅在某个条件为真时才添加参数,因此必须将命令执行移动到设置参数值的同一if。否则,将会出现未设置/添加命令参数但仍然执行该命令导致错误抛出的情况。

将您的代码更改为以下内容。

If Not firstRow Then
    item = item.Replace(""" ,", """,")
    item = item.Replace(", """, ",""")
    item = item.Replace(""",""", """__||__""")
    item = item.Replace("""", "")
    fields = item.Split("__||__")
    If Not String.IsNullOrEmpty(fields(0)) Then
        If Not fields(0).Length = 0 Then
            cmd.Parameters.AddWithValue("@gin", fields(0))
            cmd.Parameters.AddWithValue("@name", fields(1))
            cmd.Parameters.AddWithValue("@country", fields(2))
            //moved the below 3 lines to within this IF
            //this is necessary for missing @gin error to be not thrown
            firstRow = False
            cmd.Transaction = insertTrans
            cmd.ExecuteNonQuery()
        End If
    End If
End If

答案 1 :(得分:0)

cmd.Parameters.AddWithValue("gin", fields(0)) cmd.Parameters.AddWithValue("name", fields(1)) cmd.Parameters.AddWithValue("country", fields(2))

制作AddWithValue时删除@。