(1)连接数据库
public static void BulkToDB(DataTable dt)
{
//数据库连接
SqlConnection sqlCon = new SqlConnection("data source=.;initial catalog=Blog;user id=sa;password=123456;multipleactiveresultsets=True;application name=EntityFramework");
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlCon);
//数据表的名称
bulkCopy.DestinationTableName = "actionlogs";
bulkCopy.BatchSize = dt.Rows.Count;
try
{
sqlCon.Open();
if (dt != null && dt.Rows.Count != )
{
bulkCopy.WriteToServer(dt);
}
}
catch (Exception ex)
{ throw ex;
}
finally
{
sqlCon.Close();
if (bulkCopy != null)
{
bulkCopy.Close();
}
}
}
(2)获取要添加数据的表的参数
public static DataTable GetTableSchema()
{
DataTable dt = new DataTable();
//以下为要添加数据的表的参数设置
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Guid",typeof(string)),
new DataColumn("LoginName",typeof(string)),
new DataColumn("Name",typeof(string)),
});
return dt;
}
(3)在Main方法中进行调用,执行
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
for(int multiply = ; multiply < ; multiply++)
{
//获取表的参数
DataTable dt = Program.GetTableSchema();
for(int count = multiply * ; count < (multiply + ) * ; count++)
{
DataRow dr = dt.NewRow();
dr[] = Guid.NewGuid().ToString();
dr[] = "";
dr[] = "郑**";
dt.Rows.Add(dr);
}
sw.Start();
Program.BulkToDB(dt);
sw.Stop();
Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));
}
Console.ReadLine();
}
平时积累,用于复习,如有问题,请留言,谢谢