Tuesday, July 19, 2011

SQL Helper - A C# Helper Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace CommonFunction
{
    public partial class Operations
    {
        #region public sqlhelper function

        SqlConnection conCommon = new SqlConnection();

        public DataSet ExecuteDataSet(CommandType cmdType, string cmdText)
        {
            try
            {
                DataSet dsCommon = new DataSet();
                SqlCommand cmdCommon = new SqlCommand(cmdText, conCommon);
                cmdCommon.CommandType = cmdType;
                SqlDataAdapter adpCommon = new SqlDataAdapter(cmdCommon);
                conCommon.Open();
                adpCommon.Fill(dsCommon);
                conCommon.Close();
                return dsCommon;
            }
            catch { conCommon.Close(); return null; }
        }

        public DataSet ExecuteDataSet(CommandType cmdType, string cmdText, SqlParameter[] pArray)
        {
            try
            {
                DataSet dsCommon = new DataSet();
                SqlCommand cmdCommon = new SqlCommand(cmdText, conCommon);
                cmdCommon.CommandType = cmdType;

                foreach (SqlParameter p in pArray)
                    cmdCommon.Parameters.Add(p);

                SqlDataAdapter adpCommon = new SqlDataAdapter(cmdCommon);
                conCommon.Open();
                adpCommon.Fill(dsCommon);
                conCommon.Close();
                return dsCommon;
            }
            catch { conCommon.Close(); return null; }
        }

        public int ExecuteNonQuery(CommandType cmdType, string cmdText)
        {
            try
            {
                SqlCommand cmdCommon = new SqlCommand(cmdText, conCommon);
                cmdCommon.CommandType = cmdType;

                conCommon.Open();
                int returnValue = cmdCommon.ExecuteNonQuery();
                conCommon.Close();

                return returnValue;
            }
            catch { conCommon.Close(); return 0; }
        }

        public int ExecuteNonQuery(CommandType cmdType, string cmdText, SqlParameter[] pArray)
        {
            try
            {
                SqlCommand cmdCommon = new SqlCommand(cmdText, conCommon);
                cmdCommon.CommandType = cmdType;

                foreach (SqlParameter p in pArray)
                    cmdCommon.Parameters.Add(p);

                conCommon.Open();
                int returnValue = cmdCommon.ExecuteNonQuery();
                conCommon.Close();

                return returnValue;
            }
            catch { conCommon.Close(); return 0; }
        }
        #endregion public sqlhelper function
    }
}

No comments:

Post a Comment