BCP efficient batch Import

Source: Internet
Author: User

In SQL Server, many people concatenate SQL statements by repeating the Excel data read by oledb. This is not only error-prone but also inefficient. The best way is to use BCP, that is, system. data. sqlclient. sqlbulkcopy class. Not only is the speed fast, but the code is simple. The following test code imports a sheet with more than 60 thousand pieces of data, including reading (all reading is slow). It takes about 10 seconds in my development environment, the real import process takes only 4.5 seconds.

  1. Using system;
  2. Using system. Data;
  3. Using system. Windows. forms;
  4. Using system. Data. oledb;
  5. Namespace windowsapplication2
  6. {
  7. Public partial class form1: Form
  8. {
  9. Public form1 ()
  10. {
  11. Initializecomponent ();
  12. }
  13. Private void button#click (Object sender, eventargs E)
  14. {
  15. // Test. Import Sheet 1 in Excel to sqlserver.
  16. String connstring = "Server = localhost; uid = sa; Pwd = sqlgis; database = Master ";
  17. System. Windows. Forms. openfiledialog FD = new openfiledialog ();
  18. If (FD. showdialog () = dialogresult. OK)
  19. {
  20. Transferdata (FD. filename, "sheet1", connstring );
  21. }
  22. }
  23. Public void transferdata (string excelfile, string sheetname, string connectionstring)
  24. {
  25. Dataset DS = new dataset ();
  26. Try
  27. {
  28. // Obtain all data
  29. String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + excelfile + ";" + "extended properties = Excel 8.0 ;";
  30. Oledbconnection conn = new oledbconnection (strconn );
  31. Conn. open ();
  32. String strexcel = "";
  33. Oledbdataadapter mycommand = NULL;
  34. Strexcel = string. Format ("select * from [{0} $]", sheetname );
  35. Mycommand = new oledbdataadapter (strexcel, strconn );
  36. Mycommand. Fill (DS, sheetname );
  37. // Create a table if the target table does not exist
  38. String strsql = string. Format ("If object_id (& apos; {0} & apos;) is null create table {0} (", sheetname );
  39. Foreach (system. Data. datacolumn C in DS. Tables [0]. columns)
  40. {
  41. Strsql + = string. Format ("[{0}] varchar (255),", C. columnname );
  42. }
  43. Strsql = strsql. Trim (& apos;, & apos;) + ")";
  44. Using (system. Data. sqlclient. sqlconnection sqlconn = new system. Data. sqlclient. sqlconnection (connectionstring ))
  45. {
  46. Sqlconn. open ();
  47. System. Data. sqlclient. sqlcommand command = sqlconn. createcommand ();
  48. Command. commandtext = strsql;
  49. Command. executenonquery ();
  50. Sqlconn. Close ();
  51. }
  52. // Use bcp to import data
  53. Using (system. Data. sqlclient. sqlbulkcopy BCP = new system. Data. sqlclient. sqlbulkcopy (connectionstring ))
  54. {
  55. BCP. sqlrowscopied + = new system. Data. sqlclient. sqlrowscopiedeventhandler (bcp_sqlrowscopied );
  56. BCP. batchsize = 100; // number of rows transmitted each time
  57. BCP. policyafter = 100; // number of rows prompted by the progress
  58. BCP. destinationtablename = sheetname; // target table
  59. BCP. writetoserver (Ds. Tables [0]);
  60. }
  61. }
  62. Catch (exception ex)
  63. {
  64. System. Windows. Forms. MessageBox. Show (ex. Message );
  65. }
  66. }
  67. // Progress display
  68. Void bcp_sqlrowscopied (Object sender, system. Data. sqlclient. sqlrowscopiedeventargs E)
  69. {
  70. This. Text = E. rowscopied. tostring ();
  71. This. Update ();
  72. }
  73. }
  74. }

The above transferdata can be used directly. If you need to consider it carefully, you can use oledb to obtain the table structure of Excel and add columnmappings to set the control field, in this way, you can achieve the same effect as data transmission of sqlserver.

Getoledbschematable:
Using system;
Namespace consoleapplication11
...{
Class Program
...{
Public static void main ()
...{
Getexcelfileinfo (@ "C: a.xls ");
}
Private Static void getexcelfileinfo (string path)
...{
String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + path + ";" + "extended properties = Excel 8.0 ;";
System. Data. oledb. oledbconnection conn = new system. Data. oledb. oledbconnection (strconn );
Conn. open ();
System. Data. datatable table = conn. getoledbschematable (system. Data. oledb. oledbschemaguid. Tables, null );

Foreach (system. Data. datarow Drow in table. Rows)
...{
String tablename = Drow ["table_name"]. tostring ();
Console. writeline (tablename + ":");
System. Data. datatable tablecolumns = conn. getoledbschematable (system. Data. oledb. oledbschemaguid. columns, new object []... {null, null, tablename, null });
Foreach (system. Data. datarow drowcolumns in tablecolumns. Rows)
...{
String columnname = drowcolumns ["column_name"]. tostring ();
Console. writeline ("" + columnname );
}
}
Console. readkey (true );
}
}
}

JDBC corresponds:
Rs1_stmt.exe cutequery (SQL );
Rsmd = Rs. getmetadata ();

For (INT I = 1; I <= rsmd. getcolumncount (); I ++)
If (rsmd. getcolumntype (I) = 4) // int type
Xmlcontent + = rsmd. getcolumnname (I) + "= '" + Rs. getint (rsmd. getcolumnname (I) + "'";
Else
Xmlcontent + = rsmd. getcolumnname (I) + "= '" + Rs. getstring (rsmd. getcolumnname (I) + "'";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.