SqlBulkCopy批量插入数据神器

1.简单例子

    class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
DataTable dt = GetTableSchema();
for (int i = ; i < ; i++)
{
DataRow r = dt.NewRow();
//0行未自增列,为空就好
r[] = i;
r[] = string.Format("User-{0}", i);
r[] = (decimal)i;
r[] = DateTime.Now;
r[] = i;
r[] = string.Format("remak-{0}", i);
r[] = ;
r[] = true;
dt.Rows.Add(r);
}
sw.Start();
BulkToDB(dt);
sw.Stop();
Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));
Console.ReadLine();
} public static void BulkToDB(DataTable dt)
{
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["wolfTest"].ConnectionString);
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);
bulkCopy.DestinationTableName = "wolf_example";
bulkCopy.BatchSize = dt.Rows.Count; try
{
sqlConn.Open();
if (dt != null && dt.Rows.Count != )
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConn.Close();
if (bulkCopy != null)
bulkCopy.Close();
}
} public static DataTable GetTableSchema()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]{
new DataColumn("Num",typeof(int)),
new DataColumn("Type",typeof(int)),
new DataColumn("Name",typeof(string)),
new DataColumn("Money",typeof(decimal)),
new DataColumn("CTime",typeof(DateTime)),
new DataColumn("UserID",typeof(int)),
new DataColumn("Remak",typeof(string)),
new DataColumn("Sex",typeof(int)),
new DataColumn("IsShow",typeof(bool)),
}); return dt;
} }
上一篇:Codeforces Round #327 (Div. 2) B. Rebranding C. Median Smoothing


下一篇:DBCC CheckDB遇到a database snapshot could not be created