1. 程式人生 > >C# SqlHelper封裝類

C# SqlHelper封裝類

private static readyonly string Constr=ConfigurationManager.Connectionstrings["constring"].Connectionstrings;
//執行一條SQL語句
public static int ExectueNoQuery(string sql,CommandType type,params SqlParameter[] par)
{
    using(Sqlconnection conn=new Sqlconnection(Constr))
    {
        
        using(SqlCommand cmd=new Sqlcommand(sql,conn))
        {
            cmd.CommandType=type;
            if(par!=null)
            {
                com.Parameters.AddRangs(par);
            }
            conn.open();
         return  cmd.ExecuteNoQuery();
        }    
    }
} 
//ExecuteScalar返回單個值
public static int ExecuteScalar(string sql,commandType type,params SqlParameter[] par)
{
    using(Sqlconnection conn=new Sqlconnection(Constr))
    {
        using(SqlCommand cmd=new Sqlcommand(sql,conn))
        {
            cmd.commandType=type;
            if(par!=null)
            {
                 cmd.Parameters.AddRangs(par);
            }
            conn.open();
            return cmd.ExecuteScalar();
        }

    }
}

//返回ExecuteTable
public static DataTable ExecuteTable(string sql,commandType type,params SqlParameter[] par)
{
    DataSet ds=new DataSet();
    using(SqlAdapter at=new SqlAdapter(sql,Constr))
    {
        at.SelectCommand.CommandType=type;
        if(par!=null)
        {
            at.SelectCommand.Parameters.AddRangs(par)
        }
        at.fill(ds);
    }
    return ds.table[0];
}

//返回ExecuteReader查詢多列
public static SqlDataReader ExecuteReader(string sql,CommandType type,params Sqlparameter[] par)
{
    Sqlconnection conn=new Sqlconnection(Constr);
    using(SqlCommand cmd=new SqlCommand(sql,conn))
    {
        cmd.CommandType=type;
        if(parms!=null)
        {
            cmd.Parameters.AddRangs(par);
        }
        try
        {
            conn.open();
        }
        catch
        {

            conn.close();
            conn.Dispoit();
            throw;
        }

    }
}