Winform最基础的DBHelper类

PS:我已经忘记了n遍了

 class DBHelper
    {
        //连接数据库
        public static string connstring = @"Data Source=DESKTOP-8HPQ7CU;Initial Catalog=ChaoShiGuanLi;Integrated Security=True";
        public static SqlConnection conn = null;
        //初始化数据库
        public static void lnitconnection() 
        {
            if (conn==null)
            {
                //对象不存在创建连接
                conn = new SqlConnection(connstring);
            } 
            if (conn.State==ConnectionState.Closed)
            {
                //对象关闭打开连接
                conn.Open();
            }
            if (conn.State==ConnectionState.Broken)
            {
                //对象中断重新连接
                conn.Close();
                conn.Open();
            }
           
        }
        //查询获取datareader
        public static SqlDataReader GetdataReader(string sqlstr) 
        {
            lnitconnection();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        //增删改操作
        public static bool ExecuteNonQuery(string sqlstr)
        {
            lnitconnection();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            int result = cmd.ExecuteNonQuery();
            conn.Close();
            return result > 0;          
        }
        //执行聚合函数
        public static object ExecuteScalar(string sqlstr)
        {
            lnitconnection();
            SqlCommand cmd = new SqlCommand(sqlstr, conn);
            object result = cmd.ExecuteScalar();          
            conn.Close();
            return result;
        }
        public static DataTable GetDataTable(string sqlStr)
        {
            lnitconnection();
            DataTable table = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(sqlStr, conn);
            dap.Fill(table);
            conn.Close();
            return table;
        }
        
    }
posted @ 2020-02-18 21:48  南墙1  阅读(92)  评论(0编辑  收藏  举报