C# winfrom DBHelper 資料庫訪問類
阿新 • • 發佈:2018-11-16
using System; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AntiSlipSys { public class DBHelper { //資料庫連線以及增刪改查 static String conn = "Data Source=.;Initial Catalog=AntiSlipSys;Integrated Security=True";//根據專案修改連線字串 SqlConnection comm = new SqlConnection(conn); SqlCommand command = null; SqlDataReader reader = null; DataSet ds = null; SqlDataAdapter adapter = null; #region 開啟資料庫連線 public void OpenConnection() { try{ comm.Open(); } catch (Exception e) { Console.WriteLine(e.Message); } } #endregion #region 關閉資料庫連線 public void CloseConnection() { try {if (reader != null) { reader.Close(); } if (comm != null) { comm.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); } } #endregion #region 資料查詢 /// <summary> /// 連線式查詢 /// </summary> /// <param name="sql">查詢的sql語句</param> /// <returns>查詢所返回的DataReader物件</returns> public SqlDataReader Query(string sql) { this.OpenConnection(); command = new SqlCommand(sql,comm); reader = command.ExecuteReader(); return reader; } #endregion #region 資料更新操作 /// <summary> /// 使用者執行資料的更新操作 I:更新 D:刪除 U:修改 /// </summary> /// <param name="sql">執行增刪改的sql語句</param> /// <returns>返回資料庫中受影響的行數</returns> public int NoQuery(string sql) { this.OpenConnection(); command = new SqlCommand(sql,comm); int result = command.ExecuteNonQuery(); this.CloseConnection(); return result; } #endregion #region 查詢單個值[聚合函式] /// <summary> /// 使用者執行資料查詢單個值[聚合函式] /// </summary> /// <param name="sql">執行查詢的sql語句</param> /// <returns>返回單個值</returns> public int Aggre(string sql) { this.OpenConnection(); command = new SqlCommand(sql, comm); int result = (int)command.ExecuteScalar(); this.CloseConnection(); return result; } #endregion #region 斷開式查詢 /// <summary> /// 斷開式查詢 /// </summary> /// <param name="sql"></param> /// <returns></returns> public DataSet GetList(string sql) { ds = new DataSet(); adapter = new SqlDataAdapter(sql,comm); adapter.Fill(ds,"Info"); return ds; } #endregion } }
完整DBHelper 資料庫操作基類