-
使用Insert循环插入(每次一条)
-
使用Bulkcopy写入;
-
1,创建一个DataTable dt 2,using (sqlBulkcopy sbc = new sqlBulkcopy(目标库连接字符串))//目标库的链接字符串 { sbc.BulkcopyTimeout = 600; sbc.BatchSize = dt.Rows.Count; sbc.DestinationTableName = "目标表名";//目标表 sbc.WritetoServer(dt); } }
-
第二种写法 sqlDataReader reader =commandSourceData.ExecuteReader(); using (sqlConnection destinationConnection = new sqlConnection(connectionString)) { destinationConnection.open(); using (sqlBulkcopy bulkcopy =new sqlBulkcopy(destinationConnection)) { bulkcopy.DestinationTableName = "dbo.BulkcopyDemoMatchingColumns"; try { bulkcopy.WritetoServer(reader); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { // Close the sqlDataReader. The sqlBulkcopy // object is automatically closed at the end // of the using block. reader.Close(); } } long countEnd = System.Convert.ToInt32( commandRowCount.ExecuteScalar()); Console.WriteLine("Ending row count = {0}", countEnd); Console.WriteLine("{0} rows were added.", countEnd - countStart); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } }
-
使用表值参数写入。
-
sqlParameter[] paramters = new sqlParameter[] { sqlParamHelper.MakeInParam("@dt",sqlDbType.Structured) }; DataSet ds = sqlHelper.ExecuteDataset(ComputingDB_ConnString, CommandType.StoredProcedure, "存储过程名", paramters); string[] sqls = new string[] { @" insert into table1 select * from @dt ", }; using (sqlConnection connection = new sqlConnection(StatDB_ConnString)) { connection.open(); sqlTransaction trans = connection.BeginTransaction(); try { string[] typeNames = new string[] { "表类型名" }; for (int i = 0; i < sqls.Length; i++) { paramters[0].Value = ds.Tables[i]; paramters[0].TypeName = typeNames[i]; sqlHelper.ExecuteNonQuery(trans, CommandType.Text, sqls[i], paramters); }; trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw; } }
总结:Insert比较适合于少量数据的添加,如果是大批量的数据,只能考虑使用Bulkcopy或表值参数方式,后俩者相比于前者会有一个量级的提升,随着数据量的提升这个差别会越来越大
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。