コード


using System;
using System.Data;
using System.Data.Odbc;

public class PostgreSQLHandler
{
    private string connectionString;

    public PostgreSQLHandler(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public void Connect()
    {
        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            try
            {
                connection.Open();
                Console.WriteLine("Connected to PostgreSQL database");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public void ExecuteSelectQuery(string query)
    {
        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            try
            {
                connection.Open();
                OdbcCommand command = new OdbcCommand(query, connection);
                OdbcDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString(0));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public void ExecuteInsertQuery(string query)
    {
        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            try
            {
                connection.Open();
                OdbcCommand command = new OdbcCommand(query, connection);
                int rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("{0} rows affected", rowsAffected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

サンプル

 

string connectionString = "Driver={PostgreSQL Unicode};Server=localhost;Port=5432;Database=mydatabase;Uid=myuser;Pwd=mypassword;";
PostgreSQLHandler handler = new PostgreSQLHandler(connectionString);

// Connect to database
handler.Connect();

// Execute SELECT query
string selectQuery = "SELECT * FROM mytable";
handler.ExecuteSelectQuery(selectQuery);

// Execute INSERT query
string insertQuery = "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')";
handler.ExecuteInsertQuery(insertQuery);