Connessione a PostgreSQL in C#

Mattepuffo's logo
Connessione a PostgreSQL in C#

Connessione a PostgreSQL in C#

In questo articolo vediamo come eseguire una connessione ad un db PostgreSQL con C#.

Per farlo useremo la libreria Npgsql che potete installare da NuGet.

Qui sotto un esempio di codice in cui eseguiamo una semplice SELECT:

using Npgsql;

public class MainClass
{
    public static void Main(string[] args)
    {
        try
        {
            string connectionString = "Host=HOST;Database=DB;User Id=USER;Password=PWD;";
            using NpgsqlConnection connection = new NpgsqlConnection(connectionString);
            connection.Open();

            using NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM persone", connection);

            using NpgsqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader["name"]);
            }
        }
        catch (NpgsqlException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

}

Nella stringa di connessione non ho inserito la porta, in quanto usiamo quella di default; in caso potete aggiungerla come parametro.

Enjoy!


Condividi

3 Commenti

  • We saw Battalion Commander of the more all in plac

    We saw Battalion Commander of the more all in place

    29/10/2024
  • Yurka who else is damned square and shoulders to r

    Yurka who else is damned square and shoulders to repeat the city center

    23/10/2024
  • You ll be of this case of anything Nobody has cut

    You ll be of this case of anything Nobody has cut off the meat better

    19/10/2024

Commentami!