关键字:.NET,SQL SERVER,SQLBULKCOPY
插入一条数据的操作(SqlCmd)。
public void InsertOneIntoSourceDB() { if (DBConnection(GetConnectionString())) { string sqlinsert = null; SqlTransaction tran = con.BeginTransaction(); SqlCommand cmd = con.CreateCommand(); cmd.Transaction = tran; try { sqlinsert = "insert into MeterMeasureHistories values(@meterMeasureID,@value,@quality,@timestamp)"; cmd.CommandText = sqlinsert; SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@meterMeasureID",SqlDbType.Int){Value = 133}, new SqlParameter("@value",SqlDbType.Float){Value = 0}, new SqlParameter("@quality",SqlDbType.NVarChar){Value = "good"}, new SqlParameter("@timestamp",SqlDbType.DateTime){Value = DateTime.Now} }; cmd.Parameters.AddRange(parameters); cmd.ExecuteNonQuery(); tran.Commit(); } catch (Exception e) { throw e; } DBShutdown(); } }
插入多条数据,利用了SqlBulkCopy、DataTable、DataRow,效率比循环高(SqlDataAdapter)。
public void InsertIntoSourceDB() { if (DBConnection(GetConnectionString())) { try { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("MeterMeasureHistoryID"), new DataColumn("MeterMeasureID"), new DataColumn("Value"), new DataColumn("Quality"), new DataColumn("Timestamp") }); foreach (var item in meterMeasureHistories) { DataRow dr = dt.NewRow(); dr[1] = item.MeterMeasureID; dr[2] = item.Value; dr[3] = item.Quality; dr[4] = item.Timestamp; dt.Rows.Add(dr); } SqlBulkCopy bulkcopy = new SqlBulkCopy(con); bulkcopy.DestinationTableName = "dbo.MeterMeasureHistories"; bulkcopy.WriteToServer(dt); } catch (Exception e) { throw e; } DBShutdown(); } }