store.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #-*- coding:utf-8 -*-
  2. from rrd import config
  3. import MySQLdb
  4. def connect_db(cfg):
  5. try:
  6. conn = MySQLdb.connect(
  7. host=cfg.DB_HOST,
  8. port=cfg.DB_PORT,
  9. user=cfg.DB_USER,
  10. passwd=cfg.DB_PASS,
  11. db=cfg.DB_NAME,
  12. use_unicode=True,
  13. charset="utf8")
  14. return conn
  15. except Exception, e:
  16. logging.getLogger().critical('connect db: %s' % e)
  17. return None
  18. class DB(object):
  19. def __init__(self, cfg):
  20. self.config = cfg
  21. self.conn = None
  22. def get_conn(self):
  23. if self.conn is None:
  24. self.conn = connect_db(self.config)
  25. return self.conn
  26. def execute(self, *a, **kw):
  27. cursor = kw.pop('cursor', None)
  28. try:
  29. cursor = cursor or self.get_conn().cursor()
  30. cursor.execute(*a, **kw)
  31. except (AttributeError, MySQLdb.OperationalError):
  32. self.conn and self.conn.close()
  33. self.conn = None
  34. cursor = self.get_conn().cursor()
  35. cursor.execute(*a, **kw)
  36. return cursor
  37. # insert one record in a transaction
  38. # return last id
  39. def insert(self, *a, **kw):
  40. cursor = None
  41. try:
  42. cursor = self.execute(*a, **kw)
  43. row_id = cursor.lastrowid
  44. self.commit()
  45. return row_id
  46. except MySQLdb.IntegrityError:
  47. self.rollback()
  48. finally:
  49. cursor and cursor.close()
  50. # update in a transaction
  51. # return affected row count
  52. def update(self, *a, **kw):
  53. cursor = None
  54. try:
  55. cursor = self.execute(*a, **kw)
  56. self.commit()
  57. row_count = cursor.rowcount
  58. return row_count
  59. except MySQLdb.IntegrityError:
  60. self.rollback()
  61. finally:
  62. cursor and cursor.close()
  63. def query_all(self, *a, **kw):
  64. cursor = None
  65. try:
  66. cursor = self.execute(*a, **kw)
  67. return cursor.fetchall()
  68. finally:
  69. cursor and cursor.close()
  70. def query_one(self, *a, **kw):
  71. rows = self.query_all(*a, **kw)
  72. if rows:
  73. return rows[0]
  74. else:
  75. return None
  76. def query_column(self, *a, **kw):
  77. rows = self.query_all(*a, **kw)
  78. if rows:
  79. return [row[0] for row in rows]
  80. else:
  81. return []
  82. def commit(self):
  83. if self.conn:
  84. try:
  85. self.conn.commit()
  86. except MySQLdb.OperationalError:
  87. self.conn = None
  88. def rollback(self):
  89. if self.conn:
  90. try:
  91. self.conn.rollback()
  92. except MySQLdb.OperationalError:
  93. self.conn = None
  94. db = DB(config)