数据的增删改查

namespace DAL
{
    class SqlHelper
    {

        static string conString = "server=.;database=SQLSchool;uid=sa;pwd=sasa";

        /// <summary>
        /// 执行查询返回结果集
        /// </summary>
        /// <param name="safeSql">存储过程名(SQL语句)</param>
        /// <param name="ps">SQL参数对象集合</param>
        /// <returns>table</returns>
        public static DataTable ExecuteTable(string safeSql,  SqlParameter[] ps)
        {
            //using 块
            using (SqlConnection con = new SqlConnection(conString))
            {
                SqlCommand cmd = new SqlCommand(safeSql, con);
                //设置命令的类型是:存储过程。如果不设,默认是执行的文本,也就是普通的SQL语句
                cmd.CommandType = CommandType.StoredProcedure;
                //默认是执行普通的SQL文本语句如:select * from student
                //cmd.CommandType = CommandType.Text;

                if (ps != null && ps.Length > 0)
                {
                    //把参数添加到命令对象的集合中
                    cmd.Parameters.AddRange(ps);
                }
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();//查询数据:ExecuteReader
                DataTable table = new DataTable();
                table.Load(reader);

                reader.Close();
                con.Close();

                return table;
            }
        }

        public static object ExecuteSingle(string safeSql, SqlParameter[] ps)//单个对象:ExecuteSingle
        {
            using (SqlConnection con = new SqlConnection(conString))
            {
                SqlCommand cmd = new SqlCommand(safeSql, con);
                cmd.CommandType = CommandType.StoredProcedure;
                if (ps != null && ps.Length > 0)
                {
                    cmd.Parameters.AddRange(ps);
                }
                con.Open();
                object result = cmd.ExecuteScalar();
                con.Close();
                return result;
            }
        }

        public static int ExecuteInsertUpdateDelete(string safeSql, SqlParameter[] ps)
        {
            using (SqlConnection con = new SqlConnection(conString))
            {
                SqlCommand cmd = new SqlCommand(safeSql, con);
                cmd.CommandType = CommandType.StoredProcedure;
                if (ps != null && ps.Length > 0)
                {
                    cmd.Parameters.AddRange(ps);
                }
                con.Open();
                int effectedRows = cmd.ExecuteNonQuery();//增、删、改:ExecuteNonQuery
                con.Close();
                return effectedRows;  //返回受影响行数(1为成功,0为失败)
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/Tianxf815/p/8858815.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值