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;