闽公网安备 35020302035485号
我有一个程序需要从Excel读取数据,并进行数据库的更新操作,我是通过循环读取Excel的数据进行拼接SQL操作的,但是这个Excel数据有十几万条,这样循环拼接的话SQL字符串的长度会达到百万级的长度,这种长度的SQL语句SQLServer进行查询会有问题吗?
我的代码类似如下:
foreach (DataRow dataRow in dt.Rows)
{
if (!string.IsNullOrEmpty(dataRow[0].ToString()) && !string.IsNullOrEmpty(dataRow[1].ToString()))
{
sql += string.Format("update uf_gysxxb set lxhszyxmc='{0}' where BANKL='{1}'; ", dataRow[1].ToString().Trim(), dataRow[0].ToString().Trim());
}
}
大批量更新,难道你没听过SQLBulkCopy这种东西吗?
public static void UpdateData<T>(List<T> list,string TableName) { DataTable dt = new DataTable("MyTable"); dt = ConvertToDataTable(list); ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SchoolSoulDataEntitiesForReport"].ConnectionString)) { using (SqlCommand command = new SqlCommand("", conn)) { try { conn.Open(); //在数据库创建要给临时表 command.CommandText = "CREATE TABLE #TmpTable(...)"; command.ExecuteNonQuery(); //把数据批量插入临时表 using (SqlBulkCopy bulkcopy = new SqlBulkCopy(conn)) { bulkcopy.BulkCopyTimeout = 660; bulkcopy.DestinationTableName = TableName; bulkcopy.WriteToServer(dt); bulkcopy.Close(); } // 更新目标表,并删除临时表 command.CommandTimeout = 300; command.CommandText = "UPDATE T SET ... FROM " + TableName + " T INNER JOIN #TmpTable Temp ON ...; DROP TABLE #TmpTable;"; command.ExecuteNonQuery(); } catch (Exception ex) { // 异常处理 } finally { conn.Close(); } } } }