Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to PostgreSQL

I use Npgsql to deal with PostgreSQL using C#. In order to connect to the database I wrote:

NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();

Open() is a void method. It doesn't return any value indicating whether it connect to the database or not. I need to show the status connected or not connected in my client app. How to do that?

like image 788
Aan Avatar asked Oct 22 '25 19:10

Aan


1 Answers

You can check value of State property:

NpgsqlConnection conn = new NpgsqlConnection(connString); 
conn.Open(); 
if (conn.State == System.Data.ConnectionState.Open) 
       Console.WriteLine("Success open postgreSQL connection."); 
conn.Close(); 

Also event StateChange is available in version greater than 2.0 of this provider.

like image 66
kmatyaszek Avatar answered Oct 24 '25 09:10

kmatyaszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!