Skip to content

Instantly share code, notes, and snippets.

@OwainWilliams
Forked from hanssens/SQL-To-DataTable.cs
Created September 17, 2019 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OwainWilliams/6eced57ab10654db91fb96076e461136 to your computer and use it in GitHub Desktop.
Save OwainWilliams/6eced57ab10654db91fb96076e461136 to your computer and use it in GitHub Desktop.
[C#] SQL Query to Databable to CSV
// Simple example for
// 1.) Read a sql server query to datatable;
// 2.) Export it to .csv
class Program
{
static void Main(string[] args)
{
var connectionString = @"data source=bla bla bla";
var selectQuery = "select * from my-table;";
var table = ReadTable(connectionString, selectQuery);
WriteToFile(table, @"C:\temp\outputfile.csv", false, ",");
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
public static DataTable ReadTable(string connectionString, string selectQuery)
{
var returnValue = new DataTable();
var conn = new SqlConnection(connectionString);
try
{
conn.Open();
var command = new SqlCommand(selectQuery, conn);
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(returnValue);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return returnValue;
}
public static void WriteToFile(DataTable dataSource, string fileOutputPath, bool firstRowIsColumnHeader = false, string seperator = ";")
{
var sw = new StreamWriter(fileOutputPath, false);
int icolcount = dataSource.Columns.Count;
if (!firstRowIsColumnHeader)
{
for (int i = 0; i < icolcount; i++)
{
sw.Write(dataSource.Columns[i]);
if (i < icolcount - 1)
sw.Write(seperator);
}
sw.Write(sw.NewLine);
}
foreach (DataRow drow in dataSource.Rows)
{
for (int i = 0; i < icolcount; i++)
{
if (!Convert.IsDBNull(drow[i]))
sw.Write(drow[i].ToString());
if (i < icolcount - 1)
sw.Write(seperator);
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment