背景

很多用户在使用阿里云云数据库SQL Server时,为了加快插入速度,都尝试使用大容量插入的方式,大家都知道,对于完整恢复模式下的数据库,大容量导入执行的所有行插入操作都会完整地记录在事务日志中。如果使用完整恢复模式,大型数据导入会导致填充事务日志的速度很快。相反,对于简单恢复模式或大容量日志恢复模式,大容量导入操作的按最小方式记录日志减少了大容量导入操作填满日志空间的可能性。另外,按最小方式记录日志的效率也比按完整方式记录日志高 。 但实际上,当大容量导入与数据库镜像共存时,会出现镜像 Suspend的情况,这个情况是由于微软在2008 R2上的BUG导致,微软已经明确表示在2008 R2不会FIXED,那么如何正确在RDS使用大容量导入并避免镜像异常,下面介绍几种方式.

实现方法

  • 通过ADO.NET SQLBulkCopy 方式
  1. 只需要将SqlBulkCopy 指定SqlBulkCopyOptions.CheckConstraints就好,即:SqlBulkCopy blkcpy = new SqlBulkCopy(desConnString, SqlBulkCopyOptions.CheckConstraints)
  2. 例如:将本地的一个大表通过SQLBulkCopy方式导入到RDS的实例中
  3. static void Main()
  4. {
  5. string srcConnString = "Data Source=(local);Integrated Security=true;
  6. Initial Catalog=testdb";
  7. string desConnString = "Data Source=****.sqlserver.rds.aliyuncs.com,3433;
  8. UserID=**;Password=**;Initial Catalog=testdb";
  9. SqlConnection srcConnection = new SqlConnection();
  10. SqlConnection desConnection = new SqlConnection();
  11. SqlCommand sqlcmd = new SqlCommand();
  12. SqlDataAdapter da = new SqlDataAdapter();
  13. DataTable dt = new DataTable();
  14. srcConnection.ConnectionString = srcConnString;
  15. desConnection.ConnectionString = desConnString;
  16. sqlcmd.Connection = srcConnection;
  17. sqlcmd.CommandText = @"
  18. SELECT top 1000000 [PersonType],[NameStyle],[Title],[FirstName],[MiddleName],
  19. [LastName] ,[Suffix],[EmailPromotion],[AdditionalContactInfo],[Demographics],NULL
  20. as rowguid,[ModifiedDate] FROM [testdb].[dbo].[Person]";
  21. sqlcmd.CommandType = CommandType.Text;
  22. sqlcmd.Connection.Open();
  23. da.SelectCommand = sqlcmd;
  24. da.Fill(dt);
  25. using (SqlBulkCopy blkcpy =
  26. new SqlBulkCopy(desConnString,SqlBulkCopyOptions.CheckConstraints))
  27. // using (SqlBulkCopy blkcpy =
  28. // new SqlBulkCopy(desConnString, SqlBulkCopyOptions.Default))
  29. {
  30. blkcpy.BatchSize = 2000;
  31. blkcpy.BulkCopyTimeout = 5000;
  32. blkcpy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
  33. blkcpy.NotifyAfter = 2000;
  34. foreach (DataColumn dc in dt.Columns)
  35. {
  36. blkcpy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
  37. }
  38. try
  39. {
  40. blkcpy.DestinationTableName = "Person";
  41. blkcpy.WriteToServer(dt);
  42. }
  43. catch (Exception ex)
  44. {
  45. Console.WriteLine(ex.Message);
  46. }
  47. finally
  48. {
  49. sqlcmd.Clone();
  50. srcConnection.Close();
  51. desConnection.Close();
  52. }
  53. }
  54. }
  55. private static void OnSqlRowsCopied(
  56. object sender, SqlRowsCopiedEventArgs e)
  57. {
  58. Console.WriteLine("Copied {0} so far...", e.RowsCopied);
  59. }
  • 通过JDBC SQLServerBulkCopy 方式
  1. 同样的道理,需要在copyOptions指定检查约束性
  2. SQLServerBulkCopyOptions copyOptions = new SQLServerBulkCopyOptions();
  3. copyOptions.setCheckConstraints(true);
  4. 测试时,请用Microsoft JDBC Drivers 6.0 sqljdbc41.jarsqljdbc4.jar及更老版本没有SQLServerBulkCopy 实现。
  5. 例如: 将本地的一个大表通过SQLServerBulkCopy方式导入到RDS的实例中
  6. import java.sql.*;
  7. import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy;
  8. import com.microsoft.sqlserver.jdbc.SQLServerBulkCopyOptions;
  9. public class Program {
  10. public static void main(String[] args)
  11. {
  12. String sourceConnectionString = "jdbc:sqlserver://localhost:1433;" +
  13. "databaseName=testdb;user=****;password=****";
  14. String destConnectionString = "jdbc:sqlserver://*****.sqlserver.rds.aliyuncs.com:3433;" +
  15. "databaseName=testdb;user=****;password=**** ";
  16. try
  17. {
  18. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  19. try (Connection sourceConnection =
  20. DriverManager.getConnection(sourceConnectionString))
  21. {
  22. try (Statement stmt = sourceConnection.createStatement())
  23. {
  24. try (ResultSet rsSourceData = stmt.executeQuery(
  25. " SELECT top 1000000 " +
  26. "[PersonType],[NameStyle],[Title],[FirstName],[MiddleName],[LastName] ," +
  27. "[Suffix],[EmailPromotion],[AdditionalContactInfo]," +
  28. "[Demographics],NULL as rowguid,[ModifiedDate] " +
  29. "FROM [testdb].[dbo].[Person]"))
  30. {
  31. try (Connection destinationConnection = DriverManager.getConnection(destConnectionString))
  32. {
  33. Statement stmt1 = destinationConnection.createStatement();
  34. long countStart = 0;
  35. try (ResultSet rsRowCount = stmt1.executeQuery(
  36. "SELECT COUNT(*) FROM dbo.Person;"))
  37. {
  38. rsRowCount.next();
  39. countStart = rsRowCount.getInt(1);
  40. System.out.println("Starting row count = " + countStart);
  41. }
  42. try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(destinationConnection))
  43. {
  44. SQLServerBulkCopyOptions copyOptions = new SQLServerBulkCopyOptions();
  45. copyOptions.setKeepIdentity(true);
  46. copyOptions.setBatchSize(2000);
  47. copyOptions.setBulkCopyTimeout(5000);
  48. //this is importance setting
  49. copyOptions.setCheckConstraints(true);
  50. bulkCopy.setBulkCopyOptions(copyOptions);
  51. bulkCopy.setDestinationTableName("dbo.Person");
  52. bulkCopy.addColumnMapping("PersonType", "PersonType");
  53. bulkCopy.addColumnMapping("NameStyle", "NameStyle");
  54. bulkCopy.addColumnMapping("Title", "Title");
  55. bulkCopy.addColumnMapping("FirstName", "FirstName");
  56. bulkCopy.addColumnMapping("MiddleName", "MiddleName");
  57. bulkCopy.addColumnMapping("LastName", "LastName");
  58. bulkCopy.addColumnMapping("Suffix", "Suffix");
  59. bulkCopy.addColumnMapping("EmailPromotion", "EmailPromotion");
  60. bulkCopy.addColumnMapping("AdditionalContactInfo", "AdditionalContactInfo");
  61. bulkCopy.addColumnMapping("Demographics", "Demographics");
  62. bulkCopy.addColumnMapping("rowguid", "rowguid");
  63. bulkCopy.addColumnMapping("ModifiedDate", "ModifiedDate");
  64. try
  65. {
  66. bulkCopy.writeToServer(rsSourceData);
  67. }
  68. catch (Exception e)
  69. {
  70. e.printStackTrace();
  71. }
  72. try (ResultSet rsRowCount = stmt1.executeQuery(
  73. "SELECT COUNT(*) FROM dbo.Person;"))
  74. {
  75. rsRowCount.next();
  76. long countEnd = rsRowCount.getInt(1);
  77. System.out.println("Ending row count = " + countEnd);
  78. System.out.println((countEnd - countStart) + " rows were added.");
  79. }
  80. }
  81. }
  82. }
  83. }
  84. }
  85. }
  86. catch (Exception e)
  87. {
  88. e.printStackTrace();
  89. }
  90. }
  91. }
  • 通过BCP方式

第一步:需要将数据BCP到本地

  1. BCP testdb.dbo.person Out "bcp_data" /t /N /U **** /P *** /S "****.sqlserver.rds.aliyuncs.com,3433"

第二步:将导出的文件直接导入到RDS的实例中,但需要指定提示:/h “CHECK_CONSTRAINTS”

  1. BCP testdb.dbo.person In "bcp_data" /C /N /q /k /h "CHECK_CONSTRAINTS" /U *** /P *** /b 500 /S "***.sqlserver.rds.aliyuncs.com,3433"
  • 通过DTS/SSIS方式

第一种:import/export data方式需要先保存SSIS包,然后修改Connection Manager的属性 ,如下图 1111111

第二种:直接使用SQL Server Business Intelligence Development Stuidio新建 SSIS包:

222222

  • 特别说明

不能在RDS通过下列两种方式进行大容量插入: 原因是基于安全考虑不提供上传文件到RDS 数据库服务器。

第一种:

  1. BULK INSERT testdb.dbo.person_in
  2. FROM N'D:\trace\bcp.txt'
  3. WITH
  4. (
  5. CHECK_CONSTRAINTS
  6. );

第二种:

  1. INSERT ... SELECT * FROM OPENROWSET(BULK...)
  • 总结

大容量导入数据会带来更快的插入,解决了用户在有大量数据导入缓慢困惑,在阿里云数据库中,你可以使用五种方式来实现业务场景,但是基于镜像的主备关系,需要特别加入一个检查约束的选项,这是写这个最佳实践的目的,一旦镜像SUSPEND,不断有DUMP文件产生,一来需要时间来修正,二来DUMP文件也会不断占用空间,但不会影响用户的可用性和可靠性。有两种方式在RDS中不能实现,另外,还可以通过ODBC来实现大容量导入,具体请参见。希望这些对大家有用,特别是阿里云云数据库使用用户。