Search code examples
c#asp.netdatabaseconnectionusing

Using keyword with creating new connection with database


I try to improve my progamming skill when it comes to database connections.

I found those 2 similar solutions on the internet, and I would like to know what the difference is, which one should I use and why?

using (OdbcConnection con = new OdbcConnection("connectionstring"))
{
       con.Open
       //QUERY
}

AND

private OdbcConnection con;

public Database()
{
    con = new OdbcConnection("connectionstring");
}

public insertPerson()
{
    con.Open();
    //QUERY
}

Solution

  • I will go for the first example. Using keyword has a idisposable interface inherited. It has automatic disposing of object after the closing code.

    On your second example. You need to make use that you will dispose the object properly.

    Either way it can connect to the database. But the first one is my preference.