✓Python software |
sql is a module that contains three classes
Insert, Update and Delete,
that simplify generating SQL statements.
Creating an Insert statement simply works like this:
query = sql.Insert(
· "TABLE",
· {"FIELD1": "'Value1'", "FIELD2": 42, "FIELD3": None}
)
print str(query) will give you (but of course without the line feeds):
INSERT INTO TABLE
· (FIELD1, FIELD2, FIELD3)
· VALUES('''Value1''', 42, NULL)
Executing the query can be done via:
cursor.execute(str(query))
or via:
query.execute(cursor)
Creating an Update statement works like this:
query = sql.Update(
· "TABLE",
· {"FIELD1": "'Value1'"},
· {"FIELD2": 42, "FIELD3": None}
)
The query generated from this object is:
UPDATE TABLE
· SET FIELD1='''Value1'''
· WHERE FIELD2=42 AND FIELD3 IS NULL
WHERE clauses that are more involved than that are currently not possible,
and probably never will.
class Command:encapsulates an SQL command and provides a
bunch of services for derived classes. def execute(self, cursor):class Insert(Command):An SQL insert command. Convert the Insert
instance to the query string with str. def __init__(self, table, set):Create a new Insert instance.
Arguments are table, the table name,
and set, the dictionary with the field names
as keys and the field values as values. None will
be treated as NULL. class Update(Command):An SQL update command. Convert the Update
object to the query string with str. def __init__(self, table, set, where):Create a new Insert instance.
Arguments are table, the table name,
set, the dictionary with the field names
as keys and the field values as values and
where, a dictionary that maps field names
to required field values. None will be treated as
NULL for both set and where. class Delete(Command):An SQL delete command. Convert the Delete
object to the query string with str. def __init__(self, table, where):Create a new Delete instance.
Arguments are table, the table name and
where, a dictionary that maps field names
to required field values. None will be treated as
NULL for both set and where.
|