SqlHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using EMISOnline.DataLogic.Repositories;
  8. namespace EMISOnline.DataLogic.ExamSetting
  9. {
  10. public class SqlHelper
  11. {
  12. public paperRepository PaperRepository { get; set; }
  13. public DataSet Query(string storedProcedure, params KeyValuePair<string, object>[] param)
  14. {
  15. using (var connection = new SqlConnection(PaperRepository.UnitOfWork.Database.Connection.ConnectionString))
  16. {
  17. var cmd = new SqlCommand(storedProcedure, connection);
  18. cmd.CommandType = System.Data.CommandType.StoredProcedure;
  19. foreach (var kv in param)
  20. {
  21. var p = cmd.CreateParameter();
  22. p.ParameterName = kv.Key;
  23. p.Value = kv.Value ?? DBNull.Value;
  24. cmd.Parameters.Add(p);
  25. }
  26. var sqlAdapter = new SqlDataAdapter(cmd);
  27. var ds = new DataSet();
  28. sqlAdapter.Fill(ds);
  29. return ds;
  30. }
  31. }
  32. public void Execute(string storedProcedure, params KeyValuePair<string, object>[] param)
  33. {
  34. using (var connection = new SqlConnection(PaperRepository.UnitOfWork.Database.Connection.ConnectionString))
  35. {
  36. var cmd = new SqlCommand(storedProcedure, connection);
  37. cmd.CommandType = System.Data.CommandType.StoredProcedure;
  38. foreach (var kv in param)
  39. {
  40. var p = cmd.CreateParameter();
  41. p.ParameterName = kv.Key;
  42. p.Value = kv.Value ?? DBNull.Value;
  43. cmd.Parameters.Add(p);
  44. }
  45. try
  46. {
  47. cmd.Connection.Open();
  48. cmd.ExecuteNonQuery();
  49. }
  50. finally
  51. {
  52. if (cmd.Connection.State == ConnectionState.Open)
  53. cmd.Connection.Close();
  54. }
  55. }
  56. }
  57. }
  58. }