AccessDBHelper.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.OleDb;
  5. using System.Linq;
  6. using System.Text;
  7. namespace UAS_MES.DataOperate
  8. {
  9. class AccessDBHelper
  10. {
  11. private string _fileName;
  12. private string _connectionString;
  13. private OleDbConnection _odcConnection;
  14. public AccessDBHelper(string fileName)
  15. {
  16. this._fileName = fileName;
  17. this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";";
  18. }
  19. public void Open()
  20. {
  21. try
  22. {
  23. // 建立连接
  24. this._odcConnection = new OleDbConnection(this._connectionString);
  25. // 打开连接
  26. this._odcConnection.Open();
  27. }
  28. catch (Exception)
  29. {
  30. throw new Exception("嘗試打开 " + this._fileName + " 失敗, 請確認文件是否存在!");
  31. }
  32. }
  33. public void Close()
  34. {
  35. this._odcConnection.Close();
  36. }
  37. public DataSet GetDataSet(string sql)
  38. {
  39. DataSet ds = new DataSet();
  40. try
  41. {
  42. OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this._odcConnection);
  43. adapter.Fill(ds);
  44. }
  45. catch (Exception)
  46. {
  47. throw new Exception("sql語句: " + sql + " 執行失敗!");
  48. }
  49. return ds;
  50. }
  51. }
  52. }