ahmed elbarbary

ahmed elbarbary

  • 1.1k
  • 950
  • 42.1k

How to write this function ExecutedateTable with block using

Jun 2 2020 6:24 PM

I work on csharp 5.0 I need to custom this function as best practice by using block to destroy connection after finish

so How to use Using block as below

using(sql connection=new sql connection)
{
}

my function i need to customize as below :
  1. static object synObj = new object();  
  2. public static DataTable ExecuteDataTablesp(string sql, SqlConnection dbConnection, DbParameter[] @params = null, CommandType cmdType = CommandType.StoredProcedure)    
  3.     {  
  4.         SqlCommand cmd = null;    
  5.         SqlDataAdapter da = null;    
  6.             
  7.             if (dbConnection == null)    
  8.             {    
  9.                     dbConnection = (SqlConnection)InitializeConnection();    
  10.             }  
  11.             switch (Provider)    
  12.             {    
  13.                 case Providers.SQLServer:    
  14.     
  15.                     cmd = new SqlCommand("", dbConnection as SqlConnection);    
  16.                     da = new SqlDataAdapter("", dbConnection as SqlConnection);  
  17.                     break;   
  18.                 default:    
  19.                     break;    
  20.             }    
  21.             if (sql == ""return new DataTable();    
  22.             DataSet ds = new DataSet();    
  23.         try    
  24.         {    
  25.             lock (synObj)    
  26.             {  
  27.                 cmd.CommandText = sql;    
  28.                 cmd.CommandType = cmdType;    
  29.                 cmd.Parameters.Clear();  
  30.                 if (@params != null && @params.Length > 0)    
  31.                 {    
  32.                     cmd.Parameters.AddRange(@params);  
  33.                 }    
  34.                     if (dbConnection.State != ConnectionState.Open)    
  35.                         dbConnection.Open();    
  36.                 cmd.CommandTimeout = 0;    
  37.                 da.SelectCommand = cmd;    
  38.                 da.Fill(ds);  
  39.             }    
  40.         }    
  41.         catch    
  42.         {  
  43.         }    
  44.         return ds.Tables[0];    
  45.     }    
  46.  static IDbConnection InitializeConnection()    
  47.     {    
  48.         switch (_Provider)    
  49.         {    
  50.             case Providers.SQLServer:    
  51.                     
  52.                 return new SqlConnection(GlobalVariables.con);    
  53.         }    
  54.         return new SqlConnection();    
  55.     }  
 

Brought to you by: JavaScript SDK for Bold BI dashboard and analytics embedding. Free trial.

Answers (1)