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!
c# postgresql database npgsql nuget
3 Commenti
We saw Battalion Commander of the more all in place
29/10/2024Yurka who else is damned square and shoulders to repeat the city center
23/10/2024You ll be of this case of anything Nobody has cut off the meat better
19/10/2024