Tuesday, October 18, 2011

Common Connection String for All Database(Sql,MySql,Oracle ,Access....)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
namespace SearchEngine.QueryExecutor
{
    public class DataAccess
    {
        //Input
        public string inConnectionString = "";
        public string inProviderName = "";

        IDbConnection objConnection;
        IDbCommand objCommand;
        IDbDataAdapter objAdapter;
        IDbTransaction objTransaction;
        DbProviderFactory objProvidersFactory;

        DataSet dsData;
        DataTable dtData;
     
        private void GetMysqlConnection()
        {
            try
            {
                objProvidersFactory = DbProviderFactories.GetFactory(inProviderName);
                objConnection = objProvidersFactory.CreateConnection();
                objConnection.ConnectionString = inConnectionString;
                objConnection.Open();    
            }
            catch (System.Exception Ex)
            {
                objConnection = null;
            }

        }
     
     
        #region EXECUTE DATASET
        public DataSet ExecuteDataSet(CommandType cmdType, string CommandText)
        {
            try
            {
                dsData = new DataSet(); // Create new instance to dsData
                GetMysqlConnection();
                if (objConnection != null)
                {
                    objTransaction = objConnection.BeginTransaction();

                    objCommand = objProvidersFactory.CreateCommand();

                    //objCommand.CommandText = "select * from tbl_int_category";
                    objCommand.CommandTimeout = 0;
                    objCommand.CommandText = CommandText;
                    objCommand.CommandType = CommandType.Text;
                    objCommand.Transaction = objTransaction;
                    objCommand.Connection = objConnection;
                    objAdapter = objProvidersFactory.CreateDataAdapter();

                    objAdapter.SelectCommand = objCommand;

                    objAdapter.Fill(dsData);
                    objTransaction.Commit();
                }
            }
            catch (System.Exception Ex)
            {
                objTransaction.Rollback();
                dsData = null; // If any errors found then ,assign the NULL value to dsData(DataSet)
            }
            finally
            {
                if (objConnection != null)
                    objConnection.Close(); // Close the Database connection
            }
            return dsData; // Return the DataSet(dsData);


        }
        #endregion
     




    }
}

No comments:

Post a Comment