Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have question regarding sql connection open and close each record (1000 times).

Some one give me an idea which is most efficient way to do

Option 1: Open and close connection for every record

Option 2: keep open the connection for all record insert

C#
public void InsertEmployment(DLAEmployeeExport item, SqlConnection sqlConnection1)
     {
         try
         {
             System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("InsertEmployment", sqlConnection1);
             cmd.CommandType = System.Data.CommandType.StoredProcedure;
             cmd.Parameters.Add("@BusinessTitle", SqlDbType.Char);
             cmd.Parameters["@BusinessTitle"].Direction = ParameterDirection.Input;
             cmd.Parameters["@BusinessTitle"].Value = item.PositionCategory;
             sqlConnection1.Open();
             cmd.ExecuteNonQuery();
         }
         catch (System.Exception se)
         {
             Console.WriteLine(se.Message);
         }
         finally
         {
             /// if the connection is not null
             if (sqlConnection1 != null)
             {
                 ///check if the connection is open, if so then close it
                 if (sqlConnection1.State == ConnectionState.Open)
                     sqlConnection1.Close();
             }
         }
     }
Posted
Updated 15-Mar-11 15:58pm
v2

I'd think the answer would be fairly obvious - keep it open until you've finished.

I'd also take a look at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx[^] since it sounds like you are doing a bulk update

Best regards
Espen Harlinn
 
Share this answer
 
Comments
shan1395 15-Mar-11 19:52pm    
Thanks Espen Harlinn,

Am not sure i can use SQL Bulk Copy,the reason is am getting 1000 records from webserivce and update my database.

Still it will open connection 1000 time,is that a right idea for my scenario to use SQL Bulk copy ?

Thanks in Advance
Please learn about connection pooling[^]

Open your connection as late as possible, close it as soon as possible. Use a database system that manages an efficient connection pool that will take care of the details of managing the most efficient lifespan of a connection.
 
Share this answer
 
Comments
thatraja 17-Mar-11 15:06pm    
5!, Deserved another platinum.....Here I come......

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900