1.简单例子
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
DataTable dt = GetTableSchema();
for (int i = 0; i < 100000; i++)
{
DataRow r = dt.NewRow();
//0行未自增列,为空就好
r[1] = i;
r[2] = string.Format("User-{0}", i);
r[3] = (decimal)i;
r[4] = DateTime.Now;
r[5] = i;
r[6] = string.Format("remak-{0}", i);
r[7] = 1;
r[8] = 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 != 0)
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;
}
}