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 の Delete

Posted at

プロジェクトの作成

mkdir Delete01
cd Delete01
dotnet new console
dotnet add package Npgsql --version 7.0.0-preview.6

フォルダー構造

$ tree -L 1
.
├── Delete01.csproj
├── Program.cs
└── obj
Program.cs
// ----------------------------------------------------------------
/*
	Program.cs

					Aug/09/2022

*/
// ----------------------------------------------------------------
using System;
using System.Data;
using System.Text;
using Npgsql;

// ----------------------------------------------------------------
public static class postgres_delete
{
// ----------------------------------------------------------------
static async Task Main (string[] args)
{
	Console.WriteLine ("*** 開始 ***");
	string	id_in = args[0];

	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();

	delete_proc(conn,id_in);

	Console.WriteLine ("*** 終了 ***");
}

// ----------------------------------------------------------------
static void delete_proc
	(NpgsqlConnection connection,string id_a)
{
	StringBuilder sb_sql = new StringBuilder
			("DELETE from cities 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 t3463
*** 開始 ***
DELETE from cities WHERE ID = 't3463'
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?