Tuesday, June 10, 2014

C#.NET - User defined SQL Helper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Summary description for clsMsSqlHelper
/// </summary>
public class clsMsSqlHelper
{
    public clsMsSqlHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    static SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["sCon"].ToString());
    static SqlCommand oCommand = null;

    public static void OpenConnection()
    {
        try
        {
            if (oConnection.State == ConnectionState.Closed)
            {
                oConnection.Open();
            }
        }
        catch (Exception ex)
        {

        }

    }

    public static void CloseConnecton()
    {
        if (oConnection.State == ConnectionState.Open)
        {
            oConnection.Close();
        }
    }


    public static DataTable dtGetTables(string sQuery, CommandType ctCommandType, params SqlParameter[] spSqlParameter)
    {
        OpenConnection();
        oCommand = new SqlCommand(sQuery, oConnection);
        oCommand.CommandType = ctCommandType;
        foreach (SqlParameter sqlPar in spSqlParameter)
        {
            oCommand.Parameters.Add(sqlPar);
        }

        SqlDataAdapter oDataAdapter = new SqlDataAdapter(oCommand);
        DataTable dtTable = new DataTable();
        oDataAdapter.Fill(dtTable);
        CloseConnecton();
        return dtTable;
    }

    public static int ExecuteNonQuery(string sQuery, CommandType ctCommandType, params SqlParameter[] spSqlParameter)
    {
        OpenConnection();
        oCommand = new SqlCommand(sQuery, oConnection);
        oCommand.CommandType = ctCommandType;
        foreach (SqlParameter sParameter in spSqlParameter)
        {
            oCommand.Parameters.Add(sParameter);
        }
        int iExecuteNonQuery = oCommand.ExecuteNonQuery();
        CloseConnecton();
        return iExecuteNonQuery;

    }


}

No comments:

Post a Comment