Friday, January 4, 2013

Common Method For Executing Insert/Update queries in C#.NET


Using the below method you'll only need to pass the insert or update queries as a array parameter. You can execute multiple parameters by passing a array to the method parameter So that this method will reduce the number of methods you need to write.


public int ExecuteCommand(string[] sqls)
        {
            numberOfRecordsAffected = 0;

            SqlConnection sqlConnection = new SqlConnection(ConnStr);
            SqlTransaction sqlTransaction = null;
            try
            {
                sqlConnection.Open();

                sqlTransaction = sqlConnection.BeginTransaction();

                foreach (string sql in sqls)
                {
                    SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection, sqlTransaction);
                    sqlCommand.CommandTimeout = 0;
                    numberOfRecordsAffected += sqlCommand.ExecuteNonQuery();
                }

                sqlTransaction.Commit();

            }
            catch
            {
                if (sqlTransaction != null)
                    sqlTransaction.Rollback();
                sqlConnection.Close();
                throw;
            }
            finally
            {
                if (sqlConnection != null)
                    sqlConnection.Close();
            }

            return numberOfRecordsAffected;
        }

No comments:
Write comments
Recommended Posts × +