ホーム » Npgsql

Npgsql」カテゴリーアーカイブ

C#(Npgsql)でPostgresqlに大量データを追加

PostgresqlにNpgsqlを使用してデータを追加するには一般的にはNpgsqlCommandでINSERTを実行。
しかし大量のデータを追加するにはこれでは時間がかかりすぎる。
その為Postgresqlのコピー機能のラッパーであるNpgsqlCopyInの使い方を記載。
Postgresqlのコピー機能についてはこちら
追加対象のテーブル
[code]
CREATE TABLE tbl_test
(
rec_no decimal(6,0) NOT NULL,
rec_name varchar(60) NOT NULL,
add_dt timestamp without time zone NOT NULL,
CONSTRAINT pkey_tbl_test PRIMARY KEY
(
rec_no
)
)
WITH (
OIDS=FALSE
);
[/code]
追加用データCSVファイル
文字コードはUTF8
改行はCRLF
デリミタはタブ
[code]
1 NAME1 2013-09-26 00:00:00
2 NAME2 2013-09-26 00:00:00
3 NAME3 2013-09-26 00:00:00
[/code]

以下はコード
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Npgsql;
namespace pcopy
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=ホスト名;User id=ID;password=パスワード;Database=DB名;SyncNotification=true;");
conn.Open();
FileStream fs = File.OpenRead(@"CSVファイルのフルパス");
NpgsqlCommand command = new NpgsqlCommand("COPY tbl_test FROM STDIN", conn);
NpgsqlCopyIn cin = new NpgsqlCopyIn(command, conn, fs);
cin.Start();
cin.End();
}
}
}
[/code]