I used to insert big data one by one. Because the computer configuration was not good, it took me half an hour to insert 0.17 million data records. That hurts!
After listening to Teacher Yang zhongke's lesson, I found a good thing. The computer with 0.25 million pieces of data configured was completed in a few seconds. What is the magic code?
I spent a lot of money to show off the Buddha.
The t_nums table contains four fields:
Numsection, addressstr, numtype, areacode
Then read the input from the text file to a datatable, and then insert the datatable into the database. The speed is too fast.
Run:
Because the code is relatively simple and does not write comments, you may not like reading help documents or leaving a message if you do not understand it...
The following code is used:
String connstr = "Data Source = WADE-PC; initial catalog = test; persist Security info = true; user id = sa; Password = 123456 ";
Datetime starttime = datetime. now;
Openfiledialog dialog = new openfiledialog ();
Dialog. Filter = "text file (*. txt) | *. txt ";
If (dialog. showdialog () = dialogresult. OK)
{
Datatable dt = new datatable ();
DT. Columns. Add ("numsection ");
DT. Columns. Add ("addressstr ");
DT. Columns. Add ("numtype ");
DT. Columns. Add ("areacode ");
Ienumerable <string> lines = file. readlines (dialog. filename, encoding. Default );
Foreach (string STR in lines)
{
String [] STRs = Str. Split ('\ t ');
Datarow ROW = DT. newrow ();
Row ["numsection"] = STRs [0];
Row ["addressstr"] = STRs [1]. tostring (). Trim ('"');
Row ["numtype"] = STRs [2]. tostring (). Trim ('"');
Row ["areacode"] = STRs [3]. tostring (). Trim ('"');
DT. Rows. Add (ROW );
}
Using (sqlbulkcopy bulkcopy = new sqlbulkcopy (connstr ))
{
Bulkcopy. destinationtablename = "t_nums ";
Bulkcopy. columnmappings. Add ("numsection", "numsection ");
Bulkcopy. columnmappings. Add ("addressstr", "addressstr ");
Bulkcopy. columnmappings. Add ("numtype", "numtype ");
Bulkcopy. columnmappings. Add ("areacode", "areacode ");
Bulkcopy. writetoserver (DT );
}
Timespan Ts = datetime. Now. Subtract (starttime );
MessageBox. Show ("inserted in total" + dt. Rows. Count + "data, time:" + ts. tostring ());