将数据从SQL Server导出到PostgreSQL

时间:2013-03-21 22:56:00

标签: c# sql-server postgresql export

我正在使用此示例将数据从SQL Server导出到PostgreSQL,当我开始导出时,300,000行需要12分钟,我可以做些什么来加快这个过程,或者你知道另一种方法呢?

string SourceDriver = "Driver={SQL Server Native Client 10.0}";
OdbcConnection SourceConnection = new OdbcConnection(SourceDriver+ ";Server=10.10.10.10;Database=sourceMSSQL;Uid=sa;Pwd=12345;");

string DestDriver = "Driver={PostgreSQL}";
OdbcConnection DestConnection = new OdbcConnection(DestDriver+ ";Server=10.10.10.11;Port=5432;Database=destPostgreSQL;Uid=postgres;Pwd=12345;");

string SourceSql = "SELECT Code, Label, Model, List, Size, Quantity, City, Family,  ExportDate FROM MovPedidosP0";
string DestSql = "INSERT INTO tmp_MovPedidosP0_t (Code, Label, Model, List, Size, Quantity, City, Family,  ExportDate) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";

using(OdbcCommand SourceCommand = new OdbcCommand(SourceSql, SourceConnection))
{
    SourceConnection.Open();
    using(OdbcDataReader SourceReader = SourceCommand.ExecuteReader())
    {
        Console.WriteLine("Exporting...");

        DestConnection.Open();

        while(SourceReader.Read())
        {
            using(OdbcCommand DestCommand = new OdbcCommand(DestSql, DestConnection))
            {
                DestCommand.Prepare();
                DestCommand.Parameters.Clear();

                for(int i=0; i<SourceReader.FieldCount; i++)
                {
                    DestCommand.Parameters.AddWithValue("?ID" + (i+1).ToString(), SourceReader[i]);
                }

                DestCommand.ExecuteNonQuery();
                TotalRows++;
            }
        }

        DestConnection.Close();
    }
}

SourceConnection.Close();

2 个答案:

答案 0 :(得分:2)

如果使用SSIS导出到文本文件并使用COPY命令导入,则更简单,可能更快。

答案 1 :(得分:0)