OLD | NEW |
(Empty) | |
| 1 # coding: utf-8 |
| 2 |
| 3 # This file is part of the Adblock Plus web scripts, |
| 4 # Copyright (C) 2006-2015 Eyeo GmbH |
| 5 # |
| 6 # Adblock Plus is free software: you can redistribute it and/or modify |
| 7 # it under the terms of the GNU General Public License version 3 as |
| 8 # published by the Free Software Foundation. |
| 9 # |
| 10 # Adblock Plus is distributed in the hope that it will be useful, |
| 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 # GNU General Public License for more details. |
| 14 # |
| 15 # You should have received a copy of the GNU General Public License |
| 16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
| 18 import itertools, MySQLdb |
| 19 |
| 20 def connect(user, password, database): |
| 21 return MySQLdb.connect( |
| 22 user=user, |
| 23 passwd=password, |
| 24 db=database, |
| 25 use_unicode=True, charset="utf8" |
| 26 ) |
| 27 |
| 28 def query(db, sql, *params, **kwargs): |
| 29 """ |
| 30 Executes the query given by the provided SQL and returns the results. |
| 31 If dict_result keyword argument is provided + True the results will be |
| 32 returned as a tuple of dictionaries, otherwise a tuple of tuples. |
| 33 """ |
| 34 dict_result=kwargs.pop('dict_result', False) |
| 35 |
| 36 try: |
| 37 if dict_result: |
| 38 cursor = db.cursor(MySQLdb.cursors.DictCursor) |
| 39 else: |
| 40 cursor = db.cursor() |
| 41 cursor.execute(sql, params) |
| 42 results = cursor.fetchall() |
| 43 finally: |
| 44 if cursor: |
| 45 cursor.close() |
| 46 return results |
| 47 |
| 48 def write(db, queries): |
| 49 """ |
| 50 This writes a given SQL string or iteratable object of tuples containing SQL |
| 51 strings and any required parameters to the database. All queries will |
| 52 be run as one transaction and rolled back on error. |
| 53 """ |
| 54 if isinstance(queries, str): |
| 55 queries = ((queries,),) |
| 56 |
| 57 try: |
| 58 cursor = db.cursor() |
| 59 try: |
| 60 for query in queries: |
| 61 sql, params = query[0], query[1:] |
| 62 cursor.execute(sql, params) |
| 63 db.commit() |
| 64 finally: |
| 65 cursor.close() |
| 66 except MySQLdb.Error: |
| 67 if db: |
| 68 db.rollback() |
| 69 raise |
OLD | NEW |