Read SQL file and write the outcome to text file
Hi All,
I can connect C# to SQL and read SQL table but i am having problem in writing the outcome to text file. I really appreciate if you could assist me. Thank you in advance.
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace RWrite
{
class OrdinalIndexer
{
static void Main(string[] args)
{
// connection string
// connection string
string connString =
@" server = (local);
database = FoodMart 2005;
integrated security = sspi";
// query
string sql = @"
select [lname] ,[fname] ,[account_num]
from
customer
";
// create connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Open connection
conn.Open();
// create command
SqlCommand cmd = new SqlCommand(sql, conn);
// create data reader
SqlDataReader rdr = cmd.ExecuteReader();
// print headings
Console.WriteLine("\t{0} {1} {2}",
"lname".PadRight(10),
"fname".PadRight(10),
"account_num".PadRight(10)
);
Console.WriteLine("\t{0} {1} {2}",
"============".PadRight(10),
"============".PadRight(10),
"============".PadRight(10)
);
// open writing file
StreamWriter w1 = new StreamWriter("c:\\2.txt");
// loop through result set
string line1;
while (rdr.Read())
{
Console.WriteLine(" {0} | {1} | {2}",
rdr[0].ToString().PadLeft(10),
rdr[1].ToString().PadLeft(10),
rdr[2].ToString().PadLeft(10)
);
w1.WriteLine(rdr); // i know the problem in this part but i really do not know how to solve it
}
// close reader
w1.Close();
rdr.Close();
Console.Read();
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e);
}
finally
{
// close connection
Console.Read();
conn.Close();
}
}
}
}
VulpesPosted Mar 11, 2011, 5:35 AM
Nony KPosted Mar 11, 2011, 6:18 AM
Nony KPosted Mar 11, 2011, 6:17 AM
Soft CornerPosted Mar 11, 2011, 5:45 AM
replace your code at w1.WriteLine(rdr); with following lines
w1.WriteLine(rdr[0].ToString().PadLeft(10));
w1.WriteLine(rdr[1].ToString().PadLeft(10));
w1.WriteLine(rdr[2].ToString().PadLeft(10));