将sql server数据集写入文本文件

时间:2014-04-20 13:36:40

标签: .net sql-server vb.net

我从我的数据库中调用了存储的procidure,它正确地获取了一些参数。现在我想将Recordset写入文本文件,我该怎么办呢?

Dim fs, a As Object
fs = CreateObject("Scripting.FileSystemObject")

'Creating Folder to temporarily hold the upload files'
'MkDir("D:\temp_output\")'

'Create the text file'
a = fs.CreateTextFile("D:\temp_output\1output.txt", True)

'Opening connection for recordsets'
adoConn = New ADODB.Connection
adoConn.Open(Connect_str)


adoCmd = New ADODB.Command
recordset = New ADODB.Recordset

With adoCmd
    'Input parameter'
    SelectedProject = "mydb"

    .CommandText = "thesp"
    .CommandType = CommandTypeEnum.adCmdStoredProc
    .Parameters.Append(.CreateParameter("@sdate", DataTypeEnum.adDecimal, ParameterDirectionEnum.adParamInput, , 20140420))
    .Parameters.Append(.CreateParameter("@Enddate", DataTypeEnum.adDecimal, ParameterDirectionEnum.adParamInput, , 20140419))
    .Parameters(0).Precision = 8
    .Parameters(1).Precision = 8

    .ActiveConnection = adoConn

End With

'Create recordset'
recordset = adoCmd.Execute

现在如何将结果写入文本文件(1)?

1 个答案:

答案 0 :(得分:1)

为什么不使用内置的.net框架类?这是一个使用DataSet的简单示例。它使您能够以XML读取和写入数据。

Imports System.Data.SqlClient

Using connection As New SqlConnection("your_cs")
    connection.Open()
    Using command As SqlCommand = connection.CreateCommand()
        command.CommandText = "thesp"
        command.CommandType = CommandType.StoredProcedure
        command.Parameters.AddWithValue("@sdate", 20140420D)
        command.Parameters.AddWithValue("@Enddate", 20140419)
        Using adapter As New SqlDataAdapter(command)
            Using ds As New DataSet()
                adapter.Fill(ds)
                ds.WriteXml("D:\temp_output\1output.txt")
            End Using
        End Using
    End Using
End Using