Demo entry 6717762

SqlHelper

   

Submitted by 111 on Feb 28, 2018 at 05:56
Language: C#. Code size: 2.5 kB.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Mvc001.Models
{
    public class SqlHelper
    {
        public static string Constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
        public static SqlDataReader ExecuteReader(string constr, string cmdstr, CommandType type, params SqlParameter[] ps)
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(cmdstr, conn);

            cmd.CommandType = type;

            if (ps.Length > 0)
            {
                cmd.Parameters.AddRange(ps);
            }

            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            return dr;
        }


        public static int ExecuteNonQuery(string constr, string cmdstr,CommandType type, params SqlParameter[] ps)
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(cmdstr, conn);

            cmd.CommandType = type;

            if (ps.Length > 0)
            {
                cmd.Parameters.AddRange(ps);
            }

           int i= cmd.ExecuteNonQuery();

           return i;
        }


        public static DataSet ExecuteDataSet(string constr, string cmdstr,CommandType type, params SqlParameter[] ps)
        {
            SqlConnection conn = new SqlConnection(constr);
       
            SqlDataAdapter sda = new SqlDataAdapter(cmdstr, conn);       

            sda.SelectCommand.CommandType=type;

            if (ps.Length > 0)
            {
                sda.SelectCommand.Parameters.AddRange(ps);
            }

            DataSet ds = new DataSet();

            sda.Fill(ds);               

            return ds;
        }


        public static object ExecuteScalar(string constr, string cmdstr,CommandType type, params SqlParameter[] ps)
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(cmdstr, conn);

            cmd.CommandType = type;

            if (ps.Length > 0)
            {
                cmd.Parameters.AddRange(ps);
            }

            object o = cmd.ExecuteScalar();

            return o;
        }

    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).