Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Database(object):
- mysql_settings = {
- }
- connection = None
- max_attempt = 3
- character = 'utf8'
- def mysql_connect(self):
- """
- Устанавливает соединение с базой данных
- """
- self.connection = mysqldb_connect(**self.mysql_settings)
- self.execute('set names %s' % self.character)
- def run_query(self, sql, attempt=0):
- """
- Выполняет запрос, обрабатывает ошибки
- 2006 - Mysql server has gone away
- 2013 - Lost connection to mysql server
- :param sql:
- :param attempt:
- """
- cursor = self.connection.cursor()
- print sql
- try:
- cursor.execute(sql)
- except Exception, e:
- err_code, err_text = e
- print "!!! %s !!!" % err_text
- if err_code in [2006, 2013] and attempt < self.max_attempt:
- self.mysql_connect()
- attempt += 1
- self.run_query(sql, attempt)
- else:
- raise e
- self.connection.commit()
- return cursor
- def execute(self, sql):
- """
- Исполняет произвольный SQL запрос
- :param sql: String
- """
- self.run_query(sql)
- def insert(self, sql):
- """
- Выполняет вставку строки в таблицу. Возвращает идентификатор добавленой записи
- :param sql: String
- :return: Integer
- """
- cursor = self.run_query(sql)
- return cursor.lastrowid
- def get_rows(self, sql):
- """
- Возвращает несколько строк
- :param sql: String
- :rtype: Iterator
- """
- cursor = self.run_query(sql)
- return cursor.fetchall()
- def get_row(self, sql):
- """
- Возвражает одну строку из запроса
- :param sql: String
- :return: Tuple
- """
- cursor = self.run_query(sql)
- print cursor
- return cursor.fetchone()
- def get_element_by_conditions(self, tablename, conditions="1"):
- """
- Вовзращает элемент по условию.
- Оставлена для совместимости
- :param tablename: String
- :param conditions: String
- :return: Tuple
- """
- sql = 'select * from %s where %s' % (tablename, conditions)
- return self.get_row(sql)
- #---------------#
- def create_db_record(self, data):
- """
- Склеивает объявления в базе данных
- :param data: Dict
- """
- opts = {
- "tablename": "offers",
- "conditions": "name = '%s' and `url` = '%s'" % (data['name'], data['url'])
- }
- row = self._Database.get_element_by_conditions(**opts)
- print row
- if row is not None:
- data.update({"id": row[0]})
- opts = {
- "tablename": "offers",
- "data": data,
- "query_type": "replace"
- }
- query = self._Database.create_insert_query(**opts)
- print query
- self._Database.execute(query)
- self.log.info("Parsed successfully: [%s]" % data['url'])
Advertisement
Add Comment
Please, Sign In to add comment