VB.Net sql数据到文本文件

时间:2015-07-30 20:41:50

标签: vb.net sqldatareader

尝试将从sql查询中恢复的数据写入visual basic 2012中的文本文件,这里有一些代码,我只需要向正确的方向推送

Imports System.Data.SqlClient
Imports System.IO

Public Class frmResults
    Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\bryan\Documents\TeamGFinalProject\BookCollection.MDF;Integrated Security=True;Connect Timeout=30")
    Dim cmd As New SqlCommand
    Dim dr As SqlDataReader
    Dim table As New DataTable("sales")

Private Sub frmResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cmd.Connection = cn
End Sub

Private Sub BtnReport_Click(sender As Object, e As EventArgs) Handles BtnReport.Click
    cn.Open()
    cmd.CommandText = "select * from sales  where ord_date BETWEEN '" & dtpStart.Text & "' AND '" & dtpEnd.Text & "' Order BY ord_date;"

    Using sw As StreamWriter = New StreamWriter("Dates.txt")
        Dim reader As SqlDataReader = cmd.ExecuteReader()

        sw.WriteLine(reader)
        reader.Close()
    End Using

    cn.Close()
End Sub

End Class

3 个答案:

答案 0 :(得分:1)

从SqlDataReader读取时,您需要读取一行结果(SqlDataReader.Read),对其执行某些操作,然后转到下一条记录,直到获得所需内容为止。您可以使用SqlDataReader.GetValues方法立即从行中获取所有列值。

建议:使用参数来构建命令文本(see here)。

Private Sub BtnReport_Click(sender As Object, e As EventArgs) Handles BtnReport.Click       
    cn.Open()
    cmd.CommandText = "select * from sales  where ord_date BETWEEN '" & dtpStart.Text & "' AND '" & dtpEnd.Text & "' Order BY ord_date;"

    Using sw As StreamWriter = New StreamWriter("Dates.txt")
        Using reader As SqlDataReader = cmd.ExecuteReader()
            Dim values(reader.FieldCount - 1) As Object

            While reader.Read
                reader.GetValues(values)

                sw.WriteLine(String.Join(vbTab, values))
            End While
        End Using
    End Using

    cn.Close()

答案 1 :(得分:0)

你非常接近。

SqlDataReader对象有点类似于StreamReader或其他读者对象。您需要做的是使用reader对象迭代您的数据。在阅读时,字段将填充到reader对象中。然后,您可以将该数据写出来。这是一个简单的工作示例:

While (reader.Read)
   'Get data row by row
   Dim row_data(reader.FieldCount - 1) As String
   Dim i As Integer
   For i = 0 To reader.FieldCount - 1
       row_data(i) = reader(i).ToString
   Next

   'Build a single string (simplistic CSV style)
   String.Join(",",row_data)

   'Write to file
   sw.WriteLine(reader)
End While

这可能不是处理此问题的最有效方法,但它应该让您了解正在发生的事情。

答案 2 :(得分:0)

您需要遍历结果集并写入文件。

这是一个简单的例子。

How to stream data from sqldatareader to a text file in VB.Net