SQL Server 批量写入数据记录
这里写的记录了几种批量写入数据库的方法,有大部分都是别人实践过的,以后如果有新的快速的方法在进行增加。
一、使用SqlBulkCopy类,进行批量插入数据
这个的效率是最高的,进行一下备注,后面再增加测试代码。
一下备注网络寻找的代码,后面去进行验证。修改成自己的能够很好使用的。
public void ExecuteSqlBulkCopy(DataTable dt) { using (SqlConnection conn = new SqlConnection(GetConnectionString)) { SqlBulkCopy bulk = new SqlBulkCopy(conn); bulk.DestinationTableName = "TestTable"; bulk.BatchSize = dt.Rows.Count; if (dt != null && dt.Rows.Count != 0) { conn.Open(); bulk.WriteToServer(dt); } bulk.Close(); } }
二、使用数据库事务进行数据批量写入
这个方法用的比较多,可以对多个表的记录进行操作,然后一次性进行修改,如果中间出错,可以进行回滚操作。
/// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static int ExecuteSqlTran(List<String> SQLStringList) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = connection; SqlTransaction tx = connection.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } finally { cmd.Dispose(); connection.Close(); } } }
三、拼装SQL语句进行数据批量写入
这个方法以前使用过,感觉效率低下,对于批量写入数据的时候,会对其他操作照成影响,强烈不推荐.
/// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = 600; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } finally { cmd.Dispose(); connection.Close(); } } } }
上面的只是对自己的需要的知识进行记录。
路在前进的人眼中是没有尽头的!