SqlHelper

private static readonly string str = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
        public static DataTable GetTable(string sql)
        {
            DataTable dt = new DataTable();
            using (SqlDataAdapter sda = new SqlDataAdapter(sql, str))
            {
                sda.Fill(dt);
            }
            return dt;
        }
        public static int ExecuteNonQuery(string sql, params SqlParameter[] param)
        {
            using (SqlConnection con = new SqlConnection(str))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddRange (param);
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }
        public static object ExecuteScalar(string sql, params SqlParameter[] param)
        {
            using (SqlConnection con = new SqlConnection(str))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddRange  (param);
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }
        public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] param)
        {
            SqlConnection con = new SqlConnection(str);

            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                cmd.Parameters.AddRange(param);
                try
                {
                    con.Open();
                    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

posted @ 2014-04-01 13:43  crazyair  阅读(122)  评论(0编辑  收藏  举报