Alex Rivera | Logout

How often should connection be closed/opened?

Asked 2011-12-26T18:45:43.297
11

I am writing into two tables on SQL server row by row from C#.

My C# app is passing parameters into 2 stored procedures which are each inserting rows into tables.

Each time I call a stored procedure I open and then close the connection.

I need to write about 100m rows into the database.

Should I be closing and opening the connection every time I call the stored procedure?

Here is an example what I am doing:

public static void Insert_TestResults(TestResults testresults)
        {
            try
            {
                DbConnection cn = GetConnection2();
                cn.Open();

                // stored procedure
                DbCommand cmd = GetStoredProcCommand(cn, "Insert_TestResults");
                DbParameter param;

                param = CreateInParameter("TestName", DbType.String);
                param.Value = testresults.TestName;
                cmd.Parameters.Add(param);


                if (testresults.Result != -9999999999M)
                {
                    param = CreateInParameter("Result", DbType.Decimal);
                    param.Value = testresults.Result;
                    cmd.Parameters.Add(param);
                }


                param = CreateInParameter("NonNumericResult", DbType.String);
                param.Value = testresults.NonNumericResult;
                cmd.Parameters.Add(param);

                param = CreateInParameter("QuickLabDumpID", DbType.Int32);
                param.Value = testresults.QuickLabDumpID;
                cmd.Parameters.Add(param);
                // execute
                cmd.ExecuteNonQuery();

                if (cn.State == ConnectionState.Open)
                    cn.Close();

            }
            catch (Exception e)
            {

                throw e;
            }

        }

Here is the stored procedure on the server:

USE [SalesDWH]
GO
/****** Object:  StoredProcedure [dbo].[I
Edit
Report

2 Answers

1

If it is multiuser then close connection once you finsihed with them , If single user then you can keep it open for the life time of application :)

answered 2011-12-26T18:48:43.317
1

SQL has been conceived and optimized to work on sets of records. If you work procedurally by using loops, SQL will perform badly.

I do not know if that is applicable in your case, but try using the INSERT-INTO-SELECT-FROM statement instead.

It is a good practice to close the connection, if you do not know how long it will take, until you execute the next command, however if a bunch of commands are executed in a loop, I would not close and reopen the connection each time.

answered 2011-12-26T19:31:44.297

Your Answer