Advertisement
Guest User

Untitled

a guest
Jul 6th, 2015
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. public class DataBase : Page
  2. {
  3.  
  4. protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  5.  
  6. protected static string ConnectionString;
  7.  
  8. public DataBase()
  9. {
  10. ConnectionString = GetConnectionString();
  11. }
  12.  
  13. public static String GetConnectionString()
  14. {
  15. return ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
  16. }
  17.  
  18. public static T GetValue<T>(string query)
  19. where T : IComparable, IConvertible, IEquatable<T>
  20. {
  21. Object value = GetValue(query);
  22. if (Convert.IsDBNull(value))
  23. return GetDefaultValue<T>();
  24. return (T)Convert.ChangeType(value, typeof(T));
  25. }
  26.  
  27. public static T GetDefaultValue<T>()
  28. where T : IComparable, IConvertible, IEquatable<T>
  29. {
  30. if (typeof(T) == typeof(String))
  31. return (T)(object)String.Empty;
  32. return default(T);
  33. }
  34.  
  35. private static Object GetValue(string query)
  36. {
  37. try
  38. {
  39. using (SqlConnection connection = new SqlConnection(ConnectionString))
  40. using (SqlCommand command = new SqlCommand(query, connection))
  41. {
  42. connection.Open();
  43. return command.ExecuteScalar();
  44. }
  45. }
  46. catch (Exception e)
  47. {
  48. LogQueryError(query, e);
  49. return DBNull.Value;
  50. }
  51. }
  52.  
  53. protected static void LogQueryError(string query, Exception e)
  54. {
  55. log.Error(string.Format("Error while executing Query ({0}): {1}", query, e.Message));
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement