赞
踩
先转换成DataTable 然后插入数据
1.使用最后再看看使用表值参数的效率 效率最高。
首先先创建 表值特性类型的表(此表应该与转换后的datatable的列相同不然会出错)
查看地方在:当前数据库下的 可编程性-类型-用户定义表类型
CREATE TYPE MainTable AS TABLE
(
Id Int,
[Gonghao] [varchar](20) NULL,
[Xingming] [varchar](40) NULL,
[Bumen] [varchar](40) NULL,
[KaoqinDate] [datetime] NULL,
[CreateLine] [int] NULL
)
/// <summary>
/// 批量插入数据
/// </summary>
/// <param name="dt"></param>
public ResultMsg TableValuedToDB(DataTable dt )
{
ResultMsg msg = new ResultMsg();
ServerSet oneSet = new ServerSet();
oneSet = Common.JsonToIni.GetClass<ServerSet>(Common.ConfigFiles.ConfigFile);
string ConnectString = $"Data Source={oneSet.DBAdd};Initial Catalog={oneSet.DBName};Integrated Security=false;User ID={oneSet.DBUser};Password={oneSet.DBPwd};Connection Timeout=5;";//mysql链接字符
SqlConnection sqlConn = new SqlConnection(ConnectString);
const string TSqlStatement = @"INSERT [KaoqinMain]([Gonghao],[Xingming],[Bumen],[KaoqinDate],[CreateLine]) SELECT nc.Gonghao,nc.Xingming, nc.Bumen,nc.KaoqinDate,nc.CreateLine from @NewBulkTestTvp AS nc";
SqlCommand cmd = new SqlCommand(TSqlStatement, sqlConn);
SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);
catParam.SqlDbType = SqlDbType.Structured;
//表值参数的名字叫MainTable ,上面创建的表特性()。
catParam.TypeName = "dbo.MainTable";
try
{
sqlConn.Open();
if (dt != null && dt.Rows.Count != 0)
{
cmd.ExecuteNonQuery();
msg.Success = true;
}
}
catch (Exception ex)
{
msg.Success = false;
msg.ErrMsg = ex.Message;
}
finally
{
sqlConn.Close();
}
return msg;
}
2.bulk方法主要思想是通过在客户端把数据都缓存在Table中,然后利用SqlBulkCopy一次性把Table中的数据插入到数据库
public static void BulkToDB(DataTable dt)
{
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);
bulkCopy.DestinationTableName = "BulkTestTable";
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();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。