Created
December 22, 2015 17:30
-
-
Save paulmouzas/d788ca8d1bd7bf6a43ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MySQLdb | |
from MySQLdb.cursors import DictCursor | |
class DatabaseBridge(): | |
def __init__(self, *args, **kwargs): | |
kwargs['cursorclass'] = DictCursor | |
self.cnx = MySQLdb.connect (**kwargs) | |
self.cnx.autocommit(True) | |
self.cursor = self.cnx.cursor() | |
def query_all(self, query, *args): | |
self.cursor.execute(query, *args) | |
return self.cursor.fetchall() | |
def find_unique(self, query, *args): | |
rows = self.query_all(query, *args); | |
if len(rows) == 1: | |
return rows[0] | |
return None | |
def execute(self, query, params): | |
self.cursor.execute(query, params) | |
return self.cursor.rowcount | |
def get_last_id(self): | |
return self.cnx.insert_id() | |
def close(self): | |
self.cursor.close() | |
self.cnx.close() | |
database = DatabaseBridge(**{ | |
'user': 'user', | |
'passwd': 'password', | |
'db': 'my_db' | |
}) | |
rows = database.query_all("SELECT id, name, email FROM users WHERE is_active = %s AND project = %s", (1, "My First Project")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment