0

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"]);
2
  • If you are getting an exception please include that in your question. Commented Sep 26, 2014 at 18:19
  • 1
    I'd suggest researching the using keyword and not recreating the stream every iteration of the loop. Commented Sep 26, 2014 at 18:24

3 Answers 3

1

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"]);
                }
            }    
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I found a way:

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

Comments

0
        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 !

4 Comments

Can you add a title to the column ?
@user3888775 what do you mean by title to the column, I don't understand you
If the file gets saved as a csv format it gets table column titles
@user3888775 here I made edit in the while loop check it. If there is nothing more you can accept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.