DBHandler.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Text;
  7. namespace UAS_DXFORM
  8. {
  9. class DBHandler
  10. {
  11. //SqlConnection数据库连接对象
  12. public SqlConnection localConnection = null;
  13. //构造函数中初始化连接对象,传入数据库服务名,数据库实例名,用户名和密码
  14. public DBHandler(string server, string dataBase, string id, string pwd)
  15. {
  16. String connectionString = "Data Source=" + server + ";Initial Catalog=" + dataBase
  17. + ";User ID=" + id + ";Password=" + pwd;
  18. this.localConnection = new SqlConnection(connectionString);
  19. }
  20. //创建对象后调用该方法判断是否能够成功连接
  21. public int checkValidate(ref string errMsg)
  22. {
  23. try
  24. {
  25. this.localConnection.Open();
  26. }
  27. catch (Exception ex)
  28. {
  29. errMsg = "[Connecting failed]" + ex.Message;
  30. return -1;
  31. }
  32. return 0;
  33. }
  34. //操作数据库前调用
  35. private void prepareConnect()
  36. {
  37. switch (this.localConnection.State)
  38. {
  39. case ConnectionState.Broken:
  40. this.localConnection.Close(); //先正常关闭,释放资源
  41. this.localConnection.Open();
  42. break;
  43. case ConnectionState.Closed:
  44. this.localConnection.Open();
  45. break;
  46. case ConnectionState.Connecting:
  47. break;
  48. case ConnectionState.Executing:
  49. break;
  50. case ConnectionState.Fetching:
  51. break;
  52. case ConnectionState.Open:
  53. break;
  54. default:
  55. break;
  56. }
  57. }
  58. //执行Update语句,返回更新的行数
  59. public int doUpdate(string sql, ref string errMsg)
  60. {
  61. prepareConnect();
  62. SqlCommand localCommand = new SqlCommand();
  63. localCommand.CommandText = sql;
  64. localCommand.Connection = this.localConnection;
  65. try
  66. {
  67. return localCommand.ExecuteNonQuery();
  68. }
  69. catch (Exception ex)
  70. {
  71. errMsg = "[update error]" + ex.Message;
  72. return -1;
  73. }
  74. }
  75. //执行Select语句,返回DataTable结果集
  76. public void doSelect(string sql, ref DataTable dataTable, ref string errMsg)
  77. {
  78. prepareConnect();
  79. try
  80. {
  81. SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, this.localConnection);
  82. dataTable.Clear();
  83. dataAdapter.Fill(dataTable);
  84. }
  85. catch (Exception ex)
  86. {
  87. errMsg = "[select error]" + ex.Message;
  88. }
  89. }
  90. }
  91. }