simple mysql dao class for python
This is DAO class for working with mysql which may help you if you need do something quickly and don't want to use ORM:
# encoding: utf8
import MySQLdb
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class DAO(Singleton):
def __init__(self):
"""
Inits MySQL connection
"""
self._connect()
return
def _connect(self):
"""
Creates connection
"""
self.connection = MySQLdb.connect(host="localhost", \
user="mysql_user", \
passwd="mysql_password", \
db="mysql_db", \
port=3306)
return
def _get_cursor(self):
"""
Pings connection and returns cursor
"""
try:
self.connection.ping()
except:
self._connect()
return self.connection.cursor()
def get_row(self, query):
"""
Fetchs one row
"""
cursor = self._get_cursor()
cursor.execute(query)
row = cursor.fetchone()
cursor.close()
return row
def get_rows(self, query):
"""
Fetchs all rows
"""
cursor = self._get_cursor()
cursor.execute(query)
rows = cursor.fetchall()
cursor.close()
return rows
def execute(self, query):
"""
Executes query for update, delete
"""
cursor = self._get_cursor()
cursor.execute(query)
cursor.close()
return
It was cold there but it's beautiful all seasons.











