Mark
Mark

Reputation: 4873

How to reference SQL connection

I'm just learning asp.net/C# and am building my first application.

In my application, I am rendering data from sql on almost every view.

My controllers are getting large, because every time I make a request, I'm using somthing like:

try
  {
     sqlConnection = new SqlConnection(dbConnectionString);
     SqlCommand command = new SqlCommand("sp_Test", sqlConnection);
     command.CommandType = CommandType.StoredProcedure;
     sqlConnection.Open();
     return command.ExecuteNonQuery();
     sqlConnection.Close();
  }
catch (SqlException ex)
  {
     Console.WriteLine("SQL Error" + ex.Message.ToString());
     return 0;
  }

Is there a way to turn the sql into a simple using block?

Maybe something like:

using(myConnection){
           SqlCommand command = new SqlCommand("sp_Test", sqlConnection);
           command.CommandType = CommandType.StoredProcedure;
}

Upvotes: 0

Views: 1406

Answers (2)

Ajay Kelkar
Ajay Kelkar

Reputation: 4621

There are many better approaches do it. You can create a SqlHelper class that can be used to execute stored procedures and SQL queries and also return DataReader and DataTable/DataSets.

public class SqlHelper
{
   public SqlHelper(string connString)
   {
   }

   public DataSet GetDatasetByCommand(string Command);
   public SqlDataReader GetReaderBySQL(string strSQL);
   public SqlDataReader GetReaderByCmd(string Command);
   public SqlConnection GetSqlConnection();
   public void CloseConnection(); 
}

You can see one such sample here:

http://www.nullskull.com/a/1295/sql-helper-class-in-c.aspx

If you want more advanced approach you can go for Enterprise Library Data Access Block http://msdn.microsoft.com/en-us/magazine/cc163766.aspx

Upvotes: 2

Vulcronos
Vulcronos

Reputation: 3456

The best thing to do is refactor that statement into a seperate method. It looks like the only thing that could vary is the name of the procedure.

So create an object with two properties, a boolean success and an error message.

Call the function and pass in the name of the sql command. Your function should run your repeated code in the try block based on the given procedure name, then return an object with true/false and an error message if the call failed. This should make your controllers much smaller. Example code for the controller:

var result = MyNewMethod("sp_Test");
if(!result.Success)
{
   Console.WriteLine(result.ErrorMessage);
   return 0;
}

Upvotes: 0

Related Questions