Home > Net >  how to properly create a postgres database connection class in c#?
how to properly create a postgres database connection class in c#?

Time:01-12

I am new to working with databases.I am using postgres database.I want to connect it to c# for my project.Since I have multiple form screen in my project, I assume it is better to create a seperate database connection class instead of using the same code in every other classes.I want to learn how to create an effective postgres database connection class in c#

CodePudding user response:

Take a look at this website: https://www.connectionstrings.com/postgresql/

This is a great resource for finding connection strings to a variety of different databases! I reference it quite a bit. There are a couple of different connection strings for postgreSql, so you will need to dtermine which one is best to use for your use case.

I wouldn't set up a special class for a connection. Instead I recommend that you use an appsettings.json or web.config file to store the connection string and call it when you need it. Check out the documentation from Microsoft: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

CodePudding user response:

There's no need to create a connection class since database connections and commands aren't complicated or expensive to create. The best practice is to create a connection and command, execute the SQL, and then dispose of both of them. The typical pattern is:

string connString = {connection string from config};
using (OdbcConnection conn = new OdbcConnection(connString)) {
    using(OdbcCommand cmd = new OdbcCommand(sql, conn) {
        // execute command
    }
}

The using construct ensures that the connection and command are closed een if there is a database error.

  •  Tags:  
  • Related