Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created January 6, 2013 15:05
Show Gist options
  • Save riyadparvez/4467808 to your computer and use it in GitHub Desktop.
Save riyadparvez/4467808 to your computer and use it in GitHub Desktop.
An extension method class which dumps a DataTable into database table using connection string and given table name
/// <summary>
/// Utility class for writing datatable to database
/// Creating table in database for that datatable using ADO.NET
/// </summary>
public static class DataTableToSql
{
/// <summary>
///
/// </summary>
/// <param name="table"></param>
/// <param name="connectionString"></param>
/// <param name="tableName"></param>
public static void WriteToDataBaseTable(this DataTable table, string connectionString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
bulkCopy.DestinationTableName = tableName;
connection.Open();
bulkCopy.WriteToServer(table);
connection.Close();
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static DataTypeEnum ConvertToAdoType(Type type)
{
if (type == typeof(int))
{
return DataTypeEnum.adInteger;
}
if (type == typeof(double))
{
return DataTypeEnum.adDouble;
}
if (type == typeof(string))
{
return DataTypeEnum.adVarWChar;
}
if (type == typeof(bool))
{
return DataTypeEnum.adBoolean;
}
if (type == typeof(DateTime))
{
return DataTypeEnum.adDBTime;
}
return DataTypeEnum.adEmpty;
}
/// <summary>
/// Create ADO.NET table from a datatable
/// </summary>
/// <param name="dataTable"></param>
/// <returns></returns>
public static Table CreateAdoxTableFromSchema(this DataTable dataTable)
{
Table table = new Table();
table.Name = dataTable.TableName;
foreach (DataColumn column in dataTable.Columns)
{
DataTypeEnum typeEnum = ConvertToAdoType(column.DataType);
table.Columns.Append(column.ColumnName, typeEnum);
}
return table;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment