プロジェクトの作成
mkdir Update01
cd Update01
dotnet new console
dotnet add package Npgsql --version 7.0.0-preview.6
フォルダー構造
$ tree -L 1
.
├── Program.cs
├── Update01.csproj
└── obj
Program.cs
// ----------------------------------------------------------------
/*
Program.cs
Aug/09/2022
*/
// ----------------------------------------------------------------
using System;
using System.Data;
using System.Text;
using Npgsql;
// ----------------------------------------------------------------
public static class postgres_update
{
// ----------------------------------------------------------------
static async Task Main (string[] args)
{
Console.WriteLine ("*** 開始 ***");
string id_in = args[0];
int population_in = int.Parse (args[1]);
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();
update_proc(conn,id_in,population_in);
Console.WriteLine ("*** 終了 ***");
}
// ----------------------------------------------------------------
static void update_proc
(NpgsqlConnection connection,string id_a,int population_a)
{
DateTime dateNow = DateTime.Now;
string str_date = dateNow.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine (str_date);
StringBuilder sb_sql = new StringBuilder
("UPDATE cities SET population = "
+ population_a + @" , date_mod = '" + str_date +
@"' WHERE id = '" + id_a + "'");
string str_sql = sb_sql.ToString ();
Console.WriteLine (str_sql);
NpgsqlCommand command = new NpgsqlCommand (str_sql,connection);
int rowsAffected = command.ExecuteNonQuery ();
Console.WriteLine ("rowsAffected = " + rowsAffected);
}
// ----------------------------------------------------------------
}
// ----------------------------------------------------------------
実行結果
$ dotnet run t3466 8932100
*** 開始 ***
2022-08-09 20:04:38
UPDATE cities SET population = 8932100 , date_mod = '2022-08-09 20:04:38' WHERE id = 't3466'
rowsAffected = 1
*** 終了 ***