Simple to use:Private voidupdatetitle (DataTable dt) {if(dt! =NULL&& dt. Rows.Count >0) { using(SqlBulkCopy SBC =NewSqlBulkCopy (sqlhelper.connectionstring)) {SBC. BatchSize= dt. Rows.Count;//Number of operations per batchSbc. Bulkcopytimeout = -;//operation allowed time-out units: seconds (the transaction does not commit when timed out)Sbc. DestinationTableName ="Tb_product_newtitle";//database corresponding table nameSBC. WriteToServer (DT); } } }
If the fields in the DataTable and the database fields do not correspond to the exception information, you need to manually bind the columns of the DataTable and the columns in the database
Note: The data type of datacolumns must be the same as the database, otherwise all kinds of typos are also case-sensitive, must pay attention to/// <summary> ///batch update data to database (DataTable column structure remains consistent with database table)/// </summary> /// <param name= "DT" ></param> Public Static voidBulkcopydata (queue<queuemessage> MyQ,intSiteID,intmax) { if(MyQ! =NULL&& Myq.count >0) { using(SqlBulkCopy SBC =NewSqlBulkCopy (Sqlhelper.con)) {Queuemessage QM=NewQueuemessage (); DataTable DT=NewDataTable (); Dt. Columns.addrange (Newdatacolumn[] {NewDataColumn ("Sender",typeof(Int32)),NewDataColumn ("Receiver",typeof(Int32)),NewDataColumn ("Content",typeof(string)),NewDataColumn ("Createtime",typeof(DateTime)),NewDataColumn ("Sendertype",typeof(int))
}); intQcount=0; if(Max >0) Qcount=Max; ElseQcount=Myq.count (); for(inti =0; i < Qcount; i++) {QM= Myq.dequeue () asQueuemessage; DataRow Dr=dt. NewRow (); dr["Sender"] =QM. Sender; dr["Receiver"] =QM. Receiver; dr["Content"] =QM. Content; dr["Createtime"] =QM. Createtime; dr["Sendertype"] =QM. Sendertype; Dt. Rows.Add (DR); }
Bind the column name of the DataTable and the column name of the database to the SBC. Columnmappings.add ("Sender","Sender"); Sbc. Columnmappings.add ("Receiver","Receiver"); Sbc. Columnmappings.add ("Content","Content"); Sbc. Columnmappings.add ("Createtime","Createtime"); Sbc. Columnmappings.add ("Sendertype","Sendertype"); Sbc. BatchSize= dt. Rows.Count;//Number of operations per batchSbc. Bulkcopytimeout = -;//operation allowed time-out units: seconds (the transaction does not commit when timed out)Sbc. DestinationTableName ="Tb_message_"+ SiteID;//database corresponding table nameSBC. WriteToServer (DT); } } }