Introduction
This time I am going to present article over SqlHelper, named Sql Database Engine. This provides methods for various data access operations over Sql Server.
Using the code
Using code is quite easy. Download the dll attached with this article. Reference it in your project and start using it. This articles intended audience are beginners / intermediate level developers.
In general what we do for accessing database result to our page is that we use to write lots data access code every time on same page, whenever required.Making your code messy and heavy for debugging or further modifications in future. This is what I did too in my early days.
This Class helps you in eliminating such messy codes and making you code lightweight and easy to understand.
Lets move with code given below:
NameSpace : I think every .Net Developer must be aware of this Name. These are as same as header files of C/C++ having definitions and declaration classes , methods , properties used here. One can create his own namespace.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
Here AmitRanjan.DataAccessBlock.DBEngine is my namespace by which I can call my class and their methods in any application. I have my class SqlDataEngine as it contains only Sql Server specific data access methods. This is a sealed class, as I dont want it to get inherited. Also made its constructor private so as to prevent creating its object using new keyword.
namespace AmitRanjan.DataAccessBlock.DBEngine
{
public sealed class SqlDataEngine
{
private SqlDataEngine() { }
Global variable for holding Connectionstring from Configuration file and instance of SqlConnection class. Made private so as to prevent its access outside the SqlDataEngine Class.
private static string connectionString = Common.ConnectionString;
private static SqlConnection connection;
EstablishConnection() : This methods checks for the current state of the SqlConnection instance, if its found open, it closes existing connection and reopens a new connection to interact with database. You have to call this method at the beginning of the Data Access Block. Something like this. Say I am trying to get Info about students and my method name is GetStudentDetails. So my method will be :
private void GetStudentDetails(int StudentID)
{
try
{
EstablishConnection();
}
catch(Exception ex){
}
I hope this will give a transparent picture of what EstablishConnection method is doing.
public static void EstablishConnection()
{
try
{
connection = new SqlConnection(connectionString);
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
connection.Open();
}
catch
{
throw new DatabaseServerNotFoundException("Unable to connect with database server. Please contact your network administrator.");
}
}
TerminateConnection : This is opposite of the EstablishConnection method. You can use it as cleanup code in finally block of your application. So that connection will get closed every time even if there is any exception.
public static void TerminateConnection()
{
if (connection != null)
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
}
}
BeginTransaction: This associates SqlTransaction with current SqlConnection,if a user wants transaction while operating on multiple tables.
Usage : Declare a instance of SqlTransaction in the Code Block.
C# : SqlTransaction transaction;
VB : Dim transaction as new SqlTransaction
In your methods with data access layer methods mentioned below like, use something like this.ExecuteNonQuery(yourSqlStatement, transaction)
private void TransactionTest( string cmdText)
{
SqlTransaction transaction = new SqlTransaction();
try
{
SqlDataEngine.EstablishConnection();
SqlDataEngine.BeginTransaction(transaction); SqlDataEngine.ExecuteNonQuery(cmdText,transaction); SqlDataEngine.CommitTransaction(); }
catch
{
SqlDataEngine.RollbackTransaction();
}
finally
{
SqlDataEngine.TerminateConnection();
}
}
I think above code block will clear almost all doubts regarding the implemetation of methods. If not please post you query below.
public static void BeginTransaction(SqlTransaction transaction)
{
if (transaction != null)
{
transaction = connection.BeginTransaction();
}
else
{
throw new NullReferenceException("Transaction object is null.");
}
}
public static void CommitTransaction(SqlTransaction transaction)
{
if (transaction != null)
{
transaction.Commit();
}
else
{
throw new NullReferenceException("Transaction object is null.");
}
}
public static void RollbackTransaction(SqlTransaction transaction)
{
if (transaction != null)
{
transaction.Rollback();
}
else
{
throw new NullReferenceException("Transaction object is null.");
}
}
public static int ExecuteNonQuery(string commandText)
{
int returnValue = 0;
using (SqlCommand command = new SqlCommand(commandText, connection))
{
returnValue = command.ExecuteNonQuery();
}
return returnValue;
}
public static int ExecuteNonQuery(string commandText, SqlParameter[] parameters)
{
int returnValue = 0;
using (SqlCommand command = new SqlCommand(commandText, connection))
{
if (parameters.Length > 0)
{
command.Parameters.AddRange(parameters);
returnValue = command.ExecuteNonQuery();
}
else
{
throw new SqlParametersException("If using Sql Parameters, count could not be Zero. ");
}
}
return returnValue;
}
public static int ExecuteNonQuery(string commandText, SqlParameter[] parameters, SqlTransaction transaction)
{
int returnValue = 0;
if (transaction != null)
{
using (SqlCommand command = new SqlCommand(commandText, connection, transaction))
{
if (parameters.Length > 0)
{
command.Parameters.AddRange(parameters);
returnValue = command.ExecuteNonQuery();
}
else
{
throw new SqlParametersException("If using Sql Parameters, count could not be Zero. ");
}
}
}
else
{
throw new NullReferenceException( "Transaction object is null.");
}
return returnValue;
}
public static DataTable ExecuteReader(string commandText)
{
DataTable dtResult = new DataTable();
using (SqlCommand command = new SqlCommand(commandText,connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
dtResult.Load(reader);
}
}
return dtResult;
}
public static DataTable ExecuteReader(string commandText, SqlParameter[] parameters)
{
DataTable dtResult = new DataTable();
using (SqlCommand command = new SqlCommand(commandText, connection))
{
if (parameters.Length > 0)
{
using (SqlDataReader reader = command.ExecuteReader())
{
dtResult.Load(reader);
}
}
else
{
throw new SqlParametersException("If using parameters, atleast one parameter should be provided.");
}
}
return dtResult;
}
public static DataTable ExecuteReader(string commandText, SqlParameter[] parameters, SqlTransaction transaction)
{
DataTable dtResult = new DataTable();
if (transaction != null)
{
using (SqlCommand command = new SqlCommand(commandText, connection, transaction))
{
if (parameters.Length > 0)
{
using (SqlDataReader reader = command.ExecuteReader())
{
dtResult.Load(reader);
}
}
else
{
throw new SqlParametersException("If using parameters, atleast one parameter should be provided.");
}
}
}
else
{
throw new NullReferenceException("Transaction object is null.");
}
return dtResult;
}
public static object ExecuteScalar(string commandText)
{
object oResult = null;
using (SqlCommand command = new SqlCommand(commandText, connection))
{
oResult = command.ExecuteScalar();
}
return oResult;
}
public static object ExecuteScalar(string commandText, SqlParameter[] parameters)
{
object oResult = null;
using (SqlCommand command = new SqlCommand(commandText, connection))
{
if (parameters.Length > 0)
{
oResult = command.ExecuteScalar();
}
else
{
throw new SqlParametersException("If using parameters, atleast one parameter should be provided.");
}
}
return oResult;
}
public static object ExecuteScalar(string commandText, SqlParameter[] parameters, SqlTransaction transaction)
{
object oResult = null;
if (transaction != null)
{
if (parameters.Length > 0)
{
using (SqlCommand command = new SqlCommand(commandText, connection, transaction))
{
oResult = command.ExecuteScalar();
}
}
else
{
throw new SqlParametersException("If using parameters, atleast one parameter should be provided.");
}
}
else
{
throw new NullReferenceException("Transaction object is null.");
}
return oResult;
}
}
}
History
Version 1.0.0.0 - Added Data Access Methods for SQL Server. In coming versions, I am going to add support for OleDb , ODBC etc too.
*Note
This article is in under editing. I will update the explanation ASAP. Please bear with us. Any comments and suggestion on improving the source is highly appreciated.
Thanks