[Python-es] Wrapper MySQL
Juan José Rojo
jjrojoc en hotmail.com
Mie Ene 16 12:44:14 CET 2008
Buscando por ahí, he encontrado este wapper para sql, os dejo el código del archivo y el link del artículo, a ver si los entendidos nos podéis desmenuzar el código, yo hay cosas como el __delitem__ y alguna otra que no he conseguido hacer funcionar, también alguna idea para mejorarlo como añadir "inner join", falta también un controlador de campos par insertar o actualizar registros de un campo en concreto, sin más y gracias por su atención.
http://www.devx.com/dbzone/Article/22093/1954?pf=true
#!/usr/bin/python
# Modify the following to support other databases:
import MySQLdb
dbmod = MySQLdb
get_tables = "show tables;" # how to get a list of tables
row_id = "_rowid" # name of the row ID keyword
import types
class table:
"""Emulates a list of DB rows, where each row is a tuple.
May also be accessed via a string, to pull entire columns.
Examples:
t = table(db, "users")
### select and organize data
t.search("id< 0: # add support for negative (from the end) indexing
item = len(self) + item
if item < 0:
raise IndexError, "index too negative"
q = q + " limit %s, 1" % (item)
self._query(q)
return self.dbc.fetchone()
else:
raise IndexError, "unsupported index type"
def __setitem__(self, key, value):
"Not yet implemented."
if isinstance(key, types.IntType):
pass
else:
raise IndexError, "index not a number"
def __delitem__(self, item):
# the method described in the article:
#q = "select %s from %s %s %s limit %s, 1" % ("_rowid", self.name, self._search, self._sort, item)
#self._query(q)
#rid = self.dbc.fetchone()[0]
#q = "delete from %s where %s=%s" % (self.name, "_rowid", rid)
#self._query(q)
# a simpler method:
rid = self[item][-1]
q = "delete from %s where %s=%s" % (self.name, row_id, rid)
self._query(q)
def insert(self, *row):
fmt = ("%s," * len(row))[:-1]
q = "insert into %s values (%s)" % (self.name, fmt)
self._query(q, row)
def __iter__(self):
self._new_cursor()
q = "select *%s from %s %s %s" % (self._row_id, self.name, self._search, self._sort)
self._query(q)
return self
def next(self):
r = self.dbc.fetchone()
if not r:
self._new_cursor()
raise StopIteration
return r
def __len__(self):
self._query("select count(*) from %s %s" % (self.name, self._search))
r = int(self.dbc.fetchone()[0])
return r
class db:
"""
A basic wrapper for databases. Usage is as follows:
d = db(user="user", passwd="password", db="database")
table_name = d.tables()[0]
t = d.table(table_name)
The parameters for connect() and __init__() are keyword arguments, given
directly to your database module.
If you access the same table from several places in your code, there is no
need to pass the table object around. This class will keep track of them
for you and provide the existing copy of a table, if one already exists.
"""
def __init__(self, **args):
self._tables = {}
if args:
self.connect(**args)
def tables(self):
q = get_tables
c = self.obj.cursor()
a = c.execute(q)
ts = []
for row in c.fetchall():
#print row
ts.append(row[0])
return ts
def table(self, name):
try:
return self._tables[name]
except:
self._tables[name] = table(self, name)
return self._tables[name]
def connect(self, **args):
self.obj = dbmod.connect(**args)
if __name__ == "__main__":
print "this file should not be executed"
_________________________________________________________________
Tecnología, moda, motor, viajes,…suscríbete a nuestros boletines para estar siempre a la última
Guapos y guapas, clips musicales y estrenos de cine.
Más información sobre la lista de distribución Python-es