参考ページ
Npgsql 7.0.0-preview.7
プロジェクトの作成
mkdir Read01
cd Read01
dotnet new console
dotnet add package Npgsql --version 7.0.0-preview.7
フォルダー構造
$ tree -L 1
.
├── Program.cs
├── Read01.csproj
└── obj
Program.cs
// ----------------------------------------------------------------
/*
Program.cs
Aug/09/2022
*/
// ----------------------------------------------------------------
using System;
using System.Data;
using Npgsql;
// ----------------------------------------------------------------
public static class postgres_read
{
// ----------------------------------------------------------------
// public static void Main (string[] args)
static async Task Main (string[] args)
{
Console.WriteLine ("*** 開始 ***");
string server="localhost";
string str_db="city";
string user="scott";
string password="tiger123";
string str_connect = "Host=" + server + ";Username="
+ user + ";Password="
+ password + ";Database=" + str_db + ";";
await using var conn = new NpgsqlConnection(str_connect);
await conn.OpenAsync();
await using (var cmd = new NpgsqlCommand("SELECT * FROM cities", conn))
await using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
string out_str = "";
out_str += reader.GetString(0) + "\t";
out_str += reader.GetString(1) + "\t";
out_str += reader.GetValue(2).ToString() + "\t";
out_str += (reader.GetValue(3)).ToString();
Console.WriteLine(out_str);
}
}
Console.WriteLine ("*** 終了 ***");
}
// ----------------------------------------------------------------
}
// ----------------------------------------------------------------
実行結果
$ dotnet run
*** 開始 ***
t3461 広島 35867 2009-4-21
t3462 福山 52146 2009-7-9
t3463 東広島 29381 2009-9-19
t3464 呉 75836 2009-7-29
t3465 尾道 18924 2009-11-2
t3466 竹原 71456 2009-10-7
t3467 三次 92391 2009-9-9
t3468 大竹 75843 2009-8-16
t3469 府中 49123 2009-10-24
*** 終了 ***
次のバージョンで確認しました。
$ dotnet --version
6.0.400