使用Npgsql将批量数据导入到数组字段中

时间:2016-05-11 12:18:02

标签: c# postgresql npgsql

我在PostgreSQL中有以下表格:

+------------+----------+                   
|   Column   |   Type   |
+------------+----------+
| name       | text     |
| keywords   | text[]   |
+------------+----------+

我想在其中插入大量行,但我无法弄清楚如何将数据插入到数组字段中。使用BeginTextImport不起作用,因为TextWriter不接受数组:

using (var writer = connection.BeginTextImport(
  "COPY table (name, keywords) FROM STDIN DELIMITER ';'"
))
{     
    foreach (var item in items)
    {
        writer.Write(item.Name + ";");
        // How to do this?
        writer.Write(item.Keywords.ToArray(), NpgsqlDbType.Array | NpgsqlDbType.Text);
    }
}

使用BeginBinaryImport会出错:“无法关闭编写器,一行仍在进行中,首先结束NpgSql ”。

using (var writer = connection.BeginBinaryImport(
  "COPY table (name, keywords) FROM STDIN (FORMAT BINARY)"
))
{     
    foreach (var item in items)
    {
        writer.StartRow();
        writer.Write(item.Name, NpgsqlDbType.Text);
        writer.Write(item.Keywords.ToArray(), NpgsqlDbType.Array | NpgsqlDbType.Text);
    }
}// Exception thrown here

我们如何将数据批量复制到数组字段?

2 个答案:

答案 0 :(得分:2)

this怎么样?它引用了你可以使用的this library(我自己没有使用它,所以我不能评论它)。

如果你不想采取额外的依赖关系,你至少可以看看它在幕后做了什么。

答案 1 :(得分:0)

错误“无法关闭书写器,一行仍在进行中,请先结束它NpgSql”,可能是因为书写器的数量。您使用的写入项少于预期的列数。