0

我在 Access 中有一个包含 A、B 和 C 列的表。我想将此表中的记录写入包含 A、B、C 和 D 列的 SQL 表中。实现它的最佳方法是什么?

我尝试使用 OleDbDataReader 和 bulkCopy,但架构差异使其变得困难:

OleDbDataReader reader;// = new OleDbDataReader();

using (OleDbConnection sourceConnection = new OleDbConnection(sourceConnectionString))
        {
            //Get data from Access
            OleDbCommand commandSourceData = new OleDbCommand("SELECT * FROM AddressLoCo;", sourceConnection);
            commandSourceData.Connection = sourceConnection;
            sourceConnection.Open();

            reader = commandSourceData.ExecuteReader();

            using (SqlConnection destinationConection = new SqlConnection(destinationConnectionString))
            {
                destinationConection.Open();
                // Set up the bulk copy object
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConection))
                {
                    bulkCopy.DestinationTableName = "dbo.AddressMaster";

                    try
                    {
                        bulkCopy.WriteToServer(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
             }
          }
4

3 回答 3

0

您应该对数据源中存在的所有列使用SqlBulkCopy.ColumnMappings :

bulkCopy.ColumnMappings.Add("A", "A");
bulkCopy.ColumnMappings.Add("B", "B");
bulkCopy.ColumnMappings.Add("C", "C");
于 2012-05-10T12:31:58.870 回答
0

使用 Access 连接,您可以在这些线上拥有一些东西。

//The square brackets contain a valid connection to SQL Server, this is most 
//easily obtained by linking a table and checking the Connect property

string ssql = @"INSERT INTO [ODBC;Description=Test;DRIVER=SQL Server;
   SERVER=servername;Trusted_Connection=Yes;
   DATABASE=Test].table_1 (Atext)
   SELECT AText FROM Table1";
string sourceConnectionString = 
   @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=z:\docs\test.accdb;";
using (OleDbConnection sourceConnection = new OleDbConnection(sourceConnectionString))
{
    OleDbCommand commandSourceData = new OleDbCommand(ssql, sourceConnection);
    commandSourceData.Connection = sourceConnection;
    sourceConnection.Open();

    commandSourceData.ExecuteNonQuery();
于 2012-05-10T13:52:45.603 回答
0

您正在使用批量复制,它期望源表和目标表的架构相同。

您需要一次处理每条记录,或者更好的是创建 SSIS 包。

于 2012-05-10T12:23:16.067 回答