zoukankan      html  css  js  c++  java
  • 万能的DBHelper帮助类

    DBHelper类:

    简单的理解就是一个工具箱,我要用锤子的时候就在里面拿,我要用剪刀的时候也可以在里面拿,前提是我们写的DBHelper够不够强大!

    软件中的四大功能:增、删、改、查  我们要实现这些功能就必须去一一对应的去写实现他们的方法,如果我们每次用到这几个功能的时候都要写实现相同的功能的方法,

    那么就会出现代码冗余的情况,这个时候我们就可以把这些常用到的功能,提取出来封装在一个DBHelper类中,这样我们就不用每次重新去写实现相同功能的代码,

    只需要带参数然后去调用你想实现什么功能的对应方法就可以了!!!

    DBHelper格式:

    public class DBHelper {
        //从配置文件中获取连接字符串
        public static string conStr = ConfigurationManager.AppSettings["conStr"];
    
        //创建连接对象
        private static SqlConnection con = null;
    
        //获取连接对象
        public static SqlConnection GetConnection() {
            if (con == null || con.ConnectionString == "") {
                con = new SqlConnection(conStr);
            }
            return con;
        }
    
        //打开 连接
        public static void OpenConnection() {
            if (con.State == ConnectionState.Closed) {
                con.Open();
            }
        }
        //关闭连接
        public static void CloseConnection() {
            if (con.State == ConnectionState.Open) {
                con.Close();
            }
        }
    
        //执行查询:返回多行多列
        public static SqlDataReader ExecuteReader(string sql, CommandType type, params SqlParameter[] para) {
            SqlConnection con = GetConnection();
            OpenConnection();
            SqlCommand com = new SqlCommand(sql, con);
            com.CommandType = type;
            com.Parameters.AddRange(para);
            SqlDataReader dr = com.ExecuteReader();
            return dr;
        }
    
        //动作查询:添加、修改、删除
        public static int ExecuteNonQuery(string sql, CommandType type, params SqlParameter[] para) {
            SqlConnection con = GetConnection();
            OpenConnection();
            SqlCommand com = new SqlCommand(sql, con);
            com.CommandType = type;
            com.Parameters.AddRange(para);
            int n = com.ExecuteNonQuery();
            CloseConnection();
            return n;
        }
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/ZhangJiXuan/p/9787807.html
Copyright © 2011-2022 走看看