Npgsql - 来自ConcurrentQueue <t>的BulkCopy

时间:2017-05-11 08:30:22

标签: bulkinsert npgsql

假设我有一个这样的方法:

public async Task BulkCopy(ConcurrentQueue<Model> modelQueue, string connectionString)
{
    while(modelQueue.IsEmpty == false)
    {
        try
        {
            using(NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                await connection.OpenAsync();

                using(var writer = connection.BeginBinaryImport("COPY myTable (Id,Name,Something,SomethingElse)"))
                {
                    // Is this what I'm supposed to do?
                    foreach(Model item in modelQueue)
                    {
                        writer.WriteRow(item);
                    }
                }
            }
        }
    }
}

Model有属性Guid Id,string Name,string Something,string SomethingElse(就像表一样)。

我可以使用WriteRow()并传入整个对象吗?这种实现方式还是我做错了吗?

1 个答案:

答案 0 :(得分:0)

答案很简单,因为ConcurrentQueue实现了IEnumerable所有我必须做的就是通过队列运行并写入数据。

In [202]: df1.query('@index.normalize() in @selec_dates')
Out[202]:
                       0
2014-06-10 00:00:00  216
2014-06-10 01:00:00  217
2014-06-10 02:00:00  218
2014-06-10 03:00:00  219
2014-06-10 04:00:00  220
2014-06-10 05:00:00  221
2014-06-10 06:00:00  222
2014-06-10 07:00:00  223
2014-06-10 08:00:00  224
2014-06-10 09:00:00  225
...                  ...
2014-06-20 14:00:00  470
2014-06-20 15:00:00  471
2014-06-20 16:00:00  472
2014-06-20 17:00:00  473
2014-06-20 18:00:00  474
2014-06-20 19:00:00  475
2014-06-20 20:00:00  476
2014-06-20 21:00:00  477
2014-06-20 22:00:00  478
2014-06-20 23:00:00  479

[72 rows x 1 columns]

这似乎可以胜任。 30000条记录所需的时间平均为540毫秒。