Link to home
Start Free TrialLog in
Avatar of sql_insider
sql_insider

asked on

VB.NET export results of sql query to textfile

Hey all,
I've a question about VB.NET and SQL Querys.
My problem of the code below is, how do I write the results of the Query into a textfile?!
The SQL connection ect...works fine....but I don't know how can i write it to a textfile (.txt)

Private Sub SqlCon()
        Dim fso = CreateObject("Scripting.FileSystemObject")
        Dim MyFile = fso.CreateTextFile("\\FILESERVER\Logs\" & Date.Today & "-" & TimeOfDay.Hour & "-" & TimeOfDay.Minute & ".txt", True)
        Dim connString As String = "CONNECTION STRING HERE"
        Dim conn As New SqlConnection(connString)
        conn.Open()
        Dim cmdString As String = "SELECT * FROM BLABLA"
        Dim cmd As New SqlCommand(cmdString, conn)
        Dim reader As SqlDataReader = cmd.ExecuteReader()

        '????
        MyFile.Writeline(reader.Item("COLUMN HERE")) 'wie mach ich das?
        '????
    End Sub

SQL
Avatar of molku
molku

You must loop through the reader and call Read(). See code (not quite sure of the VB syntax)
While reader.Read()
   MyFile.Writeline(reader.Item("COLUMN HERE")) 
End While

Open in new window

Avatar of sql_insider

ASKER

Hey molku....
my code:

        Dim reader As SqlDataReader = cmd.ExecuteReader()
        While reader.Read()
            MyFile.WriteLine(reader.Item("ruleid"))
        End While

But it doesn't work...I will get an error:
"Unhandeld exception has occurred in....
Type mismathc. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"

SQ
ASKER CERTIFIED SOLUTION
Avatar of molku
molku

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey molku.....
thank you very much.....it works fine.......great.........

Thanks again

SQ