0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.Net 6: C# で PostgreSQL の Update

Last updated at Posted at 2022-08-09

プロジェクトの作成

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
*** 終了 ***
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?