首页 > 代码库 > C#连接数据库是编写的SqlHelper

C#连接数据库是编写的SqlHelper

static class SqlHelper
    {
        private static string connStr = ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString;

        //封装方法的原则:把不变的放在方法里 变化的放到参数列表中
      
        public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection coon = new SqlConnection(connStr))
            {
                coon.Open();
                using (SqlCommand cmd = coon.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection coon = new SqlConnection(connStr))
            {
                coon.Open();
                using (SqlCommand cmd = coon.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteScalar();
                }
            }
        }

       
        //由于查询的比较小  所以 可以直接用Table
        public static DataTable ExecuteDataTable(string sql, params  SqlParameter[] parameters)
        {
            using (SqlConnection coon = new SqlConnection(connStr))
            {
                coon.Open();
                using (SqlCommand cmd = coon.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameters);

                    DataSet dataset = new DataSet();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dataset);
                    return dataset.Tables[0];
                }
            }
        }

C#连接数据库是编写的SqlHelper