user3888775
user3888775

Reputation: 113

C# Write sql query to file?

I want to write an sql query to a file, but I'm only able to write one column of the query inside the text file. How do I add more columns ?

This is my c# windows form code:

SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();

command.CommandText = "Select * from bestillinger";
con.Open();
SqlDataReader queryReader = command.ExecuteReader();

while (queryReader.Read())
{
    StreamWriter file = new StreamWriter(@"C:\Users\Michael\Desktop\query.txt");
    file.WriteLine(queryReader["ordrenr"]);

    file.Close();

}

queryReader.Close();
con.Close();

It wont allow me to write:

file.WriteLine(queryReader["ordrenr"] + queryReader["user"]);

Upvotes: 0

Views: 5607

Answers (3)

Villanite
Villanite

Reputation: 95

I realize this six years old now, but seeing as I came across this in my own searching, I felt that offering a slightly cleaner answer would be good for others, as well. Also, I can't make comments yet, so I thought I might as well submit this as an answer.

The OP's answer presents a pretty major performance issue with recreating the stream with every row, as pointed out by Magus in the comments.

Meanwhile, mybirthname's answer actually never ends up adding a header row, and if the bool included is changed to true upon creation, it'll end up making a file filled with nothing but headers.

In this particular case, I'm writing the data out in a Comma Separated Value format. The file extension can be .csv if you want to open this in a spreadsheet editor afterwards, or .txt if it's not meant to be viewed by any end user.

//Consider putting your connection string in a config file and referencing it here.
SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString);

//If possible, avoid using "Select *" and instead, select only the columns you care about to increase efficiency.
SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn);

sqlConn.Open();
SqlDataReader sdr = sqlCmd.ExecuteReader();

if (sdr.HasRows)
{
    //There's really no reason to create the StreamWriter unless you actually find some data.
    StreamWriter swExportWriter = new StreamWriter(@"C:\DataStore\Datafile.csv");

    //Now that you know you have data, go ahead and write the first line to the file as the header row.
    swExportWriter.WriteLine("ordrenr, user");

    //Now use SqlDataReader.Read() to loop through the records and write each one to the file.
    while (sdr.Read())
    {            
        swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
    }
    //Don't forget to close the StreamWriter!
    swExportWriter.Close();
}
sdr.Close();
sqlConn.Close();

If you'd like to use Using statements instead, as per Magus' suggestion (which is probably a good idea), you can also structure it like so:

using (SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString))
{
    SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn)

    sqlConn.Open();
    using (SqlDataReader sdr = sqlCmd.ExecuteReader())
    {
        if (sdr.HasRows)
        {        
            using (StreamWriter swExportWriter = new StreamWriter(@"C:\DataStore\Datafile.csv"))
            {
                swExportWriter.WriteLine("ordrenr, user");

                while (sdr.Read())
                {            
                    swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
                }
            }    
        }
    }
}

Upvotes: 1

mybirthname
mybirthname

Reputation: 18127

        static void Main(string[] args)
        {
            string connString = @"here connection string";
            SqlConnection con = new SqlConnection(connString);
            SqlCommand command = con.CreateCommand();

            command.CommandText = "Select * from Object";
            con.Open();
            SqlDataReader queryReader = command.ExecuteReader();
            StreamWriter file = new StreamWriter(@"C:\Projects\EverydayProject\test.txt");

            bool addColumns = false;
            string columnName1="Title";
            string columnName2 = "City"; 

            while (queryReader.Read())
            {
                if(addColumns)
                {
                     file.WriteLine(columnName1 + " " + columnName2);
                     addColumns = true;
                }
                else
                {
                     file.WriteLine(queryReader["Title"].ToString() + " " + queryReader["City"].ToString());
                }                      
            }

            queryReader.Close();
            con.Close();
            file.Close();
        }

This is working you should first make the objects to String() also you need to close the file at the end. Not on first iteration !

Upvotes: 0

user3888775
user3888775

Reputation: 113

I found a way:

file.WriteLine("{0},{1}", queryReader["ordrenr"], queryReader["user"]);

Upvotes: 0

Related Questions