お仕事で c# からPostgreSQL 上のデータを扱う可能性があるのでちょっと手をつけてみる。
■テスト機にPostgreSQLサーバ導入
/var/lib/pgsql/data/pg_hba.conf を書き換え(暫定)
[bash]
local all all trust
host all all 172.0.0.0/8 trust
[/bash]
/var/lib/pgsql/data/postgresql.conf を書き換え
[bash]
listen_addresses = ‘*’
[/bash]
設定リロード
[bash]
pg_ctl reload
[/bash]
テスト用DBユーザ作成
[bash]
createuser sample
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
CREATE ROLE
[/bash]
テスト用DB作成
[bash]
createdb sampledb
[/bash]
テスト用テーブル作成
[bash]
psql sampledb
CREAT TABLE sampletable (id serial,name text);
GRANT ALL ON sampletable_id_seq TO sample ;
[/bash]
テストユーザにテスト用テーブルへのアクセス権限をフルで与える
[bash]
grant ALL ON sampletable TO sample;
[/bash]
別のLinux機から接続テスト
[bash]
psql -h <ホスト名> -U sample -d sampledb
[/bash]
Linux 側(というかPostgreSQL側)の作業はここで一段落。
ここからは c# 側。
概ね方向は2系統。ODBCを使うか、npgsql を使うか。なんか、pgOLEDB.dll というものもあるらしい。よーわからん。
とりあえずnpgsqlを、
http://www.postgresql.jp/document/NPGSQL/manual/UserManual_J.htm
を参考にしながら試してみる。
http://pgfoundry.org/frs/?group_id=1000140
から Npgsql2.0.5-bin-ms.net3.5sp1.zip を入手。
展開して、適当なところにおいておく。とりあえずC:\npgsqlにおいてみた。
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
にある
gacutil.exe
をつかって
gacutil -i C:\npgsql\bin\Npgsql.dll
しておく。
まずはコンソールアプリケーションで試してみる。
Vc#2008でコンソールアプリケーションを新規作成。
頭の using が並んでいるところに
using System.Data;
using Npgsql;
を追加。
ぐは、ビルドしてみたらうごかねー。
エラー 1 型または名前空間名 'Npgsql' が見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足しています。 C:\Users\XXXXX\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 6 7 ConsoleApplication1
なので、プロジェクト→参照の追加→参照で、C:\npgsql\bin\Npgsql.dll を追加しておく。
これで「デバッグ開始」でエラーは出なくなった。
この時点でのソースはこんな感じ。
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Npgsql;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
}
[/csharp]
んでもってMainの中に、接続のための処理を書いておく。全体はこんな感じ。
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Npgsql;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=<サーバのIPアドレス>;Port=5432;User Id=sample;Database=sampledb;");
conn.Open();
conn.Close();
}
}
}
[/csharp]
■テーブルに行を追加する処理
※デバッグが終了してしまわないように確認画面を入れた。
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Npgsql;
namespace ConsoleApplication1
{
class Program
{
public static Int32 rowsaffected; // Mainの中においておいたらエラーが出たのでサンプルから変更。
public static void Main(String[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=<サーバのIPアドレス>;Port=5432;User Id=sample;Database=sampledb;");
conn.Open();
Console.WriteLine(conn.State);
NpgsqlCommand command = new NpgsqlCommand("insert into sampletable (name) values(‘TEST OK’)", conn);
try
{
rowsaffected = command.ExecuteNonQuery();
}
catch
{
Console.WriteLine("It was added {0} lines in table table1", rowsaffected);
}
finally
{
conn.Close();
}
# if DEBUG
Console.WriteLine("続行するには何かキーを押してください・・・");
Console.ReadKey();
# endif
}
}
}
[/csharp]
おおおおお、追加されてるよ。ナイスだ。
■単一の結果が返ってくるものを取得する
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Npgsql;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=<サーバのIPアドレス>;Port=5432;User Id=sample;Database=sampledb;");
conn.Open();
Console.WriteLine(conn.State);
NpgsqlCommand command = new NpgsqlCommand("select version()", conn);
string serverVersion;
try
{
serverVersion = (String)command.ExecuteScalar();
Console.WriteLine("PostgreSQL server version: {0}", serverVersion); // これはtry の中に入れてやらないとエラーになった
}
finally
{
conn.Close();
}
# if DEBUG
Console.WriteLine("続行するには何かキーを押してください・・・");
Console.ReadKey();
# endif
}
}
}
[/csharp]
■全ての問い合わせ結果を取得する
データ的に多少面白くなるようにテーブルを用意しておく。
<Linux側作業>
[bash]
CREATE TABLE sampletable2 (name text, yomi text, address text);
INSERT INTO sampletable2 VALUES (‘パンツェッタ 幸平’,'ぱんつぇった こうへい’,'panzetta_kouhei@example.com’);
INSERT INTO sampletable2 VALUES (‘村松 沙知絵’,'むらまつ さちえ’,'muramatsu_sachie@example.com’);
INSERT INTO sampletable2 VALUES (‘田代 恵望子’,'たしろ えみこ’,'tashiro_emiko@example.com’);
INSERT INTO sampletable2 VALUES (‘中島 璃子’,'なかしま りこ’,'nakashima_riko@example.com’);
INSERT INTO sampletable2 VALUES (‘畑中 恵梨香’,'はたなか えりか’,'hatanaka_erika@example.com’);
grant ALL ON sampletable2 TO sample ;
[/bash]
この手のサンプルデータを作るのは http://kazina.com/dummy/ の「なんちゃって個人情報」さんが便利。
ソースはこんな感じ。
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Npgsql;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=<サーバのIPアドレス>;Port=5432;User Id=sample;Database=sampledb;");
conn.Open();
Console.WriteLine(conn.State);
NpgsqlCommand command = new NpgsqlCommand("select * from sampletable2", conn);
try
{
NpgsqlDataReader dr = command.ExecuteReader();
int i;
while (dr.Read())
{
for (i = 0; i < dr.FieldCount; i++)
{
Console.Write("{0} \t", dr[i]);
}
Console.WriteLine();
}
}
finally
{
conn.Close();
}
# if DEBUG
Console.WriteLine("続行するには何かキーを押してください・・・");
Console.ReadKey();
# endif
}
}
}
[/csharp]
でもってこれをGUIの画面にしたときにどうやってDataGridViewに表示するのかがいまいちわかってないけど、それは又今度。とりあえずデータの出し入れはわかったので今日はここまで。