Home > Code Samples > Bulk Insert CSV File into SQL Server in C#
Bulk Insert CSV File into SQL Server in C#
C#
using (SqlConnection conn = new SqlConnection(@"Data Source=.\sql2014;Initial Catalog=Test;Integrated Security=True"))
{
conn.Open();
#region create table
using (SqlCommand createTable = new SqlCommand(@"
IF NOT EXISTS
(
SELECT *
FROM
sys.schemas s
INNER JOIN sys.tables t ON
t.[schema_id] = s.[schema_id]
WHERE
s.name = 'dbo' AND
t.name = 'Products'
)
BEGIN
CREATE TABLE dbo.Products
(
ProductID int NOT NULL,
ProductName nvarchar(40) NOT NULL,
SupplierID int NULL,
CategoryID int NULL,
QuantityPerUnit nvarchar(20) NULL,
UnitPrice money NULL CONSTRAINT DF_Products_UnitPrice DEFAULT (0),
UnitsInStock smallint NULL CONSTRAINT DF_Products_UnitsInStock DEFAULT (0),
UnitsOnOrder smallint NULL CONSTRAINT DF_Products_UnitsOnOrder DEFAULT (0),
ReorderLevel smallint NULL CONSTRAINT DF_Products_ReorderLevel DEFAULT (0),
Discontinued bit NOT NULL CONSTRAINT DF_Products_Discontinued DEFAULT (0),
Reorder bit NOT NULL
);
END", conn))
{
createTable.ExecuteNonQuery();
}
#endregion
using (CsvDataReader reader = new CsvDataReader("../../products.csv"))
using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
{
reader.Settings.HasHeaders = true;
reader.Columns.Add("int", "ProductID");
reader.Columns.Add("nvarchar", "ProductName");
reader.Columns.Add("int", "SupplierID");
reader.Columns.Add("int", "CategoryID");
reader.Columns.Add("nvarchar", "QuantityPerUnit");
reader.Columns.Add("money", "UnitPrice");
reader.Columns.Add("smallint", "UnitsInStock");
reader.Columns.Add("smallint", "UnitsOnOrder");
reader.Columns.Add("smallint", "ReorderLevel");
reader.Columns.Add("bit", "Discontinued");
reader.Columns.Add("bit", "Reorder");
reader.ReadRecord += delegate(DataReaderBase.ReadRecordEventArgs e)
{
bool discontinued = bool.Parse(e.Values["Discontinued"]);
int unitsInStock = int.Parse(e.Values["UnitsInStock"]);
int unitsOnOrder = int.Parse(e.Values["UnitsOnOrder"]);
int reorderLevel = int.Parse(e.Values["ReorderLevel"]);
bool needToReorder = false;
if (
!discontinued &&
reorderLevel > 0 &&
unitsInStock + unitsOnOrder < reorderLevel
)
{
needToReorder = true;
}
e.Values["Reorder"] = needToReorder.ToString();
};
bcp.DestinationTableName = "dbo.Products";
bcp.EnableStreaming = true;
bcp.NotifyAfter = 10;
bcp.SqlRowsCopied += delegate (object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine(e.RowsCopied.ToString("#,##0") + " rows copied.");
};
using (ValidatingDataReader validator = new ValidatingDataReader(reader, conn, bcp))
{
bcp.WriteToServer(validator);
}
}
}
|