SQLHelper

private SqlConnection conn = null;
private SqlCommand cmd = null;
private SqlDataReader sdr = null; 

  
        /// SQLHelper()用来连接数据库。
             public SQLHelper()
        {
            string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            conn = new SqlConnection(connStr);
        }


        /// 打开数据库      
        private SqlConnection GetConn()
        {
            if (conn.State == ConnectionState.Closed)
            {

                conn.Open();
            }
            return conn;
        }


        /// 该方法执行传入的SQL语句(增,删,改)--防SQL注入。
        public int ExecuteNonQuery(string cmdText, SqlParameter[] paras, CommandType ct)
    {
             int res;
             using (cmd = new SqlCommand(cmdText, GetConn()))
            {
                cmd.CommandType = ct;
                cmd.Parameters.AddRange(paras);
                res = cmd.ExecuteNonQuery();
            }
            return res;
    }


        /// 返回第一行第一列的值(不防注入)
        public string ExecuteScalar(string  sql)
        {
            string res;
            using (cmd = new SqlCommand(sql, GetConn()))
            {
                object ob = cmd.ExecuteScalar();
                res = Convert.ToString(ob);
            }
            return res;
          
        }
      
        /// 返回第一行第一列的值(防注入)
        public string ExecuteScalar(string cmdText, CommandType ct)
        {
            string res;
            using (cmd = new SqlCommand(cmdText, GetConn()))
            {
                cmd.CommandType = ct;
                object ob = cmd.ExecuteScalar();
                res = Convert.ToString(ob);
            }
            return res;
        }
 

        /// 方法执行传入的SQL语句(查询)
        public DataTable ExecuteQuery(string cmdText, CommandType ct)
        {
            DataTable dt = new DataTable();
            cmd = new SqlCommand(cmdText, GetConn());
            cmd.CommandType = ct;
             using (sdr =     cmd.ExecuteReader(CommandBehavior.CloseConnection))
             {
                 dt.Load(sdr);
             }
             return dt;
        }
    
        /// 方法执行传入的SQL语句(查询)--防止SQL注入
        public DataTable ExecuteQuery(string cmdText,SqlParameter[] paras,CommandType ct)
        {
            DataTable dt = new DataTable();
            cmd = new SqlCommand(cmdText, GetConn());
            cmd.CommandType = ct;
            cmd.Parameters.AddRange(paras);
            using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                dt.Load(sdr);
            }
            return dt;
        }

你可能感兴趣的:(sql)