Best way to close connection in a class to simplify c# DB connections for SQL queries/updates
NickName:Vexen Crabtree Ask DateTime:2017-10-19T22:54:21

Best way to close connection in a class to simplify c# DB connections for SQL queries/updates

I'm learning C#, and, have created a class to simplify what I have to do to execute an SQL query and loop through the results and also, to run an update. In both cases, pass the SQL and an optional list of parameters.

Here's the class that does the simplification:

    public db(string pQuerySQL, List<string> pParams=null) {
        //Params array replace @PARAM1, @PARAM2, @PARAM3 (etc) in the SQL
        //code would be: com.Parameters.Add(new OleDbParameter("@PARAM1", pParams[0]));
        con= new OleDbConnection(db.conString);
        com = con.CreateCommand();
        com.CommandText = pQuerySQL;
        addParamsToCom(lCom, pParams);
        con.Open();
        rs = com.ExecuteReader();
    }

    public static void runUpdate(string pUpdateSQL, List<string> pParams = null) {
        //Params array replace @PARAM1, @PARAM2, @PARAM3 (etc) in the SQL

        OleDbConnection lCon = new OleDbConnection(db.conString);
        OleDbCommand lCom = lCon.CreateCommand();
        lCom.CommandText=pUpdateSQL;
        addParamsToCom(lCom, pParams);
        lCon.Open();
        lCom.ExecuteNonQuery();
        lCon.Close();
    }

    private static void addParamsToCom(OleDbCommand pCom,List<string> pParams = null) {
        if(!(pParams is null)) {    //Add params to the SQL
            for(int i = 0;i<pParams.Count;i++) {
                pCom.Parameters.AddWithValue("@PARAM"+(i+1).ToString(), pParams[i]);
            }
        }
    }

The advantage is that the class exposes the DataReader (recordset), so you can do db.rs.Read() or use any other functionality that it has.

Passing parameters is easy. Example with one parameter (to pass none, omit the 2nd parameter and just pass the SQL):

db db = new db(
    "SELECT trackTitle FROM tracks WHERE [band]=@PARAM1",
    new List<String> { "Sisters of Mercy" }
);
while (db.rs.Read()){
    Debug.WriteLine(db.rs["trackTitle"]);
}
db.close();

[20171027: Added code to deal with parameters]

How could I make the connection close-itself as the object is destroyed (i.e. after its scope collapses)?

Copyright Notice:Content Author:「Vexen Crabtree」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46832813/best-way-to-close-connection-in-a-class-to-simplify-c-sharp-db-connections-for-s

More about “Best way to close connection in a class to simplify c# DB connections for SQL queries/updates” related questions

Best way to close connection in a class to simplify c# DB connections for SQL queries/updates

I'm learning C#, and, have created a class to simplify what I have to do to execute an SQL query and loop through the results and also, to run an update. In both cases, pass the SQL and an optional...

Show Detail

Best way to open/close DB Connection with async/await

In tutorials I found, there is always opening and closing the connection for every request, for example : import asyncio import asyncpg async def run(): conn = await asyncpg.connect(user='use...

Show Detail

To close or not to close an Oracle Connection?

My application have performance issues, so i started to investigate this from the root: "The connection with the database". The best practices says: "Open a connection, use it and close is as soon...

Show Detail

C# sql create one connection and open and close for each query

I recently inherited a C# Web app that creates a new connection for every query like so: public class QueryForm { public bool getStudents() { SqlConnection conn = new SqlConnection(

Show Detail

Best way to handle connection open and close with a For loop

I've already checked here. I am looping an opening a connection each time and I'm not sure if ASP.NET handles it with a performance hit or that it recognizes this code and optimizes it automatical...

Show Detail

what is the best way to create connection Class in C#

I have windows form that asking user name, password and databaseName, and the way I am using to connect database open to SQL injection!. I want to create different class for my connection string, a...

Show Detail

Close db connection

i've founded in the web a class that i needed. This class during her lifecycle open a connection with a local MySql db. In my code the scope of this class instance is local, like this example fun...

Show Detail

Is "connection.Close()" the best or safest way to close an SQL connection?

I've been using connection.Close(); But this is my first project in .NET and I'm not sure if I'm closing it correctly. I don't want my website to instantly die after putting it out on real hosti...

Show Detail

PyQt - How to close database connection on class destruction

If my class uses a database quite a few times (a lot of functions/properties use data from the DB), what's the best practice: to create a DB connection once at the start of the class, do whatever s...

Show Detail

Statement and Resultset close after connection close

I have recently moved to a project where I am encountering a lot of code of this nature - (This is using the jdbc postgres driver) try { Connection conn = pool.getAConnection(); //home-grown ...

Show Detail