AccessDBHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. using System.Windows;
  8. namespace UAS_MES.DataOperate
  9. {
  10. class AccessDBHelper
  11. {
  12. private string _fileName;
  13. private string _connectionString;
  14. private OleDbConnection _odcConnection = null;
  15. public AccessDBHelper(string fileName)
  16. {
  17. this._fileName = fileName;
  18. this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";";
  19. }
  20. public AccessDBHelper(string fileName,string password)
  21. {
  22. this._fileName = fileName;
  23. this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Jet OLEDB:Database Password="+password+";";
  24. }
  25. public void Open()
  26. {
  27. try
  28. {
  29. // 建立连接
  30. this._odcConnection = new OleDbConnection(this._connectionString);
  31. // 打开连接
  32. this._odcConnection.Open();
  33. }
  34. catch (Exception ex)
  35. {
  36. MessageBox.Show(ex.Message);
  37. }
  38. }
  39. public void Close()
  40. {
  41. this._odcConnection.Close();
  42. }
  43. public DataTable GetDataTable(string sql)
  44. {
  45. DataTable ds = new DataTable();
  46. OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this._odcConnection);
  47. try
  48. {
  49. adapter.Fill(ds);
  50. }
  51. catch (Exception ex)
  52. {
  53. throw new Exception("sql語句: " + sql + " 執行失敗!" + ex.Message);
  54. }
  55. adapter.Dispose();
  56. return ds;
  57. }
  58. public DataSet GetDataSet(string sql)
  59. {
  60. DataSet ds = new DataSet();
  61. OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this._odcConnection);
  62. try
  63. {
  64. adapter.Fill(ds);
  65. }
  66. catch (Exception ex)
  67. {
  68. throw new Exception("sql語句: " + sql + " 執行失敗!"+ex.Message);
  69. }
  70. adapter.Dispose();
  71. return ds;
  72. }
  73. /// <summary>
  74. /// 通过条件更新
  75. /// </summary>
  76. /// <param name="TableName"></param>
  77. /// <param name="update"></param>
  78. /// <param name="condition"></param>
  79. public string UpdateByCondition(string TableName, string update, string condition)
  80. {
  81. DataTable result = new DataTable();
  82. string sql = "update " + TableName + " set " + update + " where " + condition;
  83. OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this._odcConnection);
  84. try
  85. {
  86. adapter.Fill(result);
  87. }
  88. catch (Exception ex)
  89. {
  90. throw new Exception("sql語句: " + sql + " 執行失敗!" + ex.Message);
  91. }
  92. adapter.Dispose();
  93. return sql;
  94. }
  95. }
  96. }