import MySQLdb from MySQLdb cursors import SSCursor from django conf i

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import MySQLdb
from MySQLdb.cursors import SSCursor
from django.conf import settings
connection = MySQLdb.connect(host='localhost',
db=settings.IMPORTER_DATABASE_NAME,
user=settings.IMPORTER_DATABASE_USER,
passwd=settings.IMPORTER_DATABASE_PASSWORD,
use_unicode=True,
charset='utf8')
class ResultRow(dict):
def __getattr__(self, name):
return self[name]
def iterate_cursor(cursor):
"""
Iterate over cursor.
"""
columns = [x[0] for x in cursor.description]
for row in cursor:
yield ResultRow(dict(zip(columns, row)))
def iterate_table(name, limit=None, select=None, join=None, order=None, where=None):
cursor = connection.cursor(cursorclass=SSCursor)
limit = 'LIMIT %d' % limit if limit else ''
select = ', %s' % select if select else ''
join = ' %s ' % join if join else ''
order = ' %s ' % order if order else ''
where = ' %s ' % where if where else ''
sql = """SELECT *%s FROM %s %s %s %s %s""" % (select, name, join, where, order, limit)
cursor.execute(sql)
for user in iterate_cursor(cursor):
yield user