Hello, I'm new to vb.net. I have successfully run a simple sql query in vb.net and basically wanted to know how I can export the results from the query to a .txt file? All I really know is that I should be using StreamWriter. Does anyone have suggestions for sending, for example "SELECT column1, column2, from table1 where column1 = '1'" to a .txt file? Would it be best to first bind the data to a grid or can I skip that step? Thanks in advance

Recommended Answers

All 6 Replies

You can use a select statement to fill a DataSet/DataTable. You can then export the entire dataset to an xml file with a single call, youDataSet.WriteXml(strYourFileNameAndPath)

Exporting to a text file is a bit more involved, you have to loop thru each of the records in the datatable to extract each column field and format your line object to use the StreamWriter.

Hey, what version of VB.NET are you using?
Here is an sample of VB.NET 2005(connecting to mysql database. the syntax for MS SQL database is similar)

Dim column_1 as string
Dim column_2 as string
'creat a text file first
dim oWriter as system.io.streamwriter
oWrite = system.io.file.createtext("c:\sample.txt")
'connection string and mysqlconnect
Dim connstring as string = "server=?;database=?;user id=?;password=?"
Dim conn as new mysqlconnection(connstring)
'create selection query
Dim selectSQL as string = "Select column1, column2 from tablename"
'create selection command
dim cmd as new mysqlcommand(selectSQL, conn)
'set cmd property
cmd.CommandType = CommandType.Text
'open database
conn.open()
'create a new reader and execute the reader
Dim myreader as mysqldatareader = cmd.executereader
'read information from the database and give the values to the arguments(column_1, and column_2)
While myreader.read
        column_1 = myreader.getstring(0)
        column_2 = myreader.getstring(1)
        oWrite.Writeline(column_1," ",column_2)
        'leave a space
        oWrite.writeline()
end while
'close file
oWrite.close()

ps:
to read from existing file
change the oWrite command to

oWrite = System.io.file.opentext("c:\sample.txt")

I hope that helps :)

Works perfectly! thank you for your help

one last thing...is there anyway to make it so that the application saves as a new text file every time it is run? basically, am I able to save the file as a unique ID that the user inputs (txtpick.text in this case), so that a new text file is written for every txtpick.text name?

Figured it out. It was easy enough, I just used

Writer = System.IO.File.CreateText(txtpick.Text & ".txt")

thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.