vba如何将动态参数插入SQL批量语法

时间:2016-03-11 05:56:37

标签: sql sql-server vb.net

我正在尝试使用vb opendialog打开随机csv文件,并将csv中的数据插入到SQL Server 2014中。当涉及到硬编码数据时,它看起来很好,但对于动态随机上传它有问题。相当困难,所以请帮助我。

这是我的动态测试代码,我已经创建了与csv文件的文件格式和列名匹配的数据库,表和列:

 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim con As String = "Server=KEN-PC;Database=testData;Trusted_Connection=True;"
    Dim myStream As Stream = Nothing
    Dim openFileDialog2 As New OpenFileDialog()

    openFileDialog2.InitialDirectory = "c:\Desktop"
    openFileDialog2.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    openFileDialog2.FilterIndex = 2
    openFileDialog2.RestoreDirectory = True

    If openFileDialog2.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Try
            myStream = openFileDialog2.OpenFile()
            If (myStream IsNot Nothing) Then
                ' Insert code to read the stream here.
                TextBox2.Text = openFileDialog2.FileName
                Dim conString As String = OpenFileDialog1.FileName

                Try
                    Using connection As New SqlConnection(connetionString)
                        connection.ConnectionString = con
                        sql = "BULK INSERT cvtest
                        FROM" & "'constring'" & "With ( FIELDTERMINATOR = ',', 
                          ROWTERMINATOR = '\n')"
                        connection.Open()
                        adapter = New SqlDataAdapter(sql, connection)
                        adapter.Fill(ds)

                        connection.Close()
                    End Using

                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try

            End If
        Catch Ex As Exception
            MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
        Finally
            ' Check this again, since we need to make sure we didn't throw an exception on open.
            If (myStream IsNot Nothing) Then
                myStream.Close()
            End If
        End Try
    End If
End Sub

我像PHP一样执行它,但它抛出了无法匹配的列的错误,但我认为情况并非如此,因为我已经创建了相同的东西,我使用硬代码数据测试它,它回复了我的成功,谢谢阅读和希望建议。

1 个答案:

答案 0 :(得分:0)

<啊>啊哈......我自己解决了,关键是sql命令无法捕获我指定的动态参数,所以我做了以下工作

                        sql = "
                        BULK INSERT cvtest
                        FROM 'close' With ( FIELDTERMINATOR = ',', 
                          ROWTERMINATOR = '\n')"
                        sql = sql.Replace("close", conString)