Here is some example code to give you a flavour of the various ways the module operates.
The user connects to a database and obtain a cursor as follows:
import web.database connection = web.database.connect(adapter='MySQLdb', database='testDatabase') cursor = connection.cursor()
They interact with the database through a series of methods which form a database abstraction layer. Each method builds an SQL string in accordance with the syntax of the driver and executes it according to the options specified:
results = cursor.select(columns=['name'], tables=['testTable'], where=cursor.where("name = 'James'"), fetch=True)
Results could instead be retrieved as follows if fetch was False
:
results = cursor.fetchall(format='dict')
Results are automatically converted to the defined types and returned in the correct format.
web.database cursors also support the execute() statement and qmark style parameter substitutions:
cursor.execute("select name from testTable where name = ?", ['James'])
The SQL is parsed, the parameters converted to SQL and inserted in the correct places and the appropriate abstraction layer method is executed.
The web.database field types are stored in a table in the database so that the web.database driver knows the field types and names of the fields in the tables so that conversions can be made.
The Connection
object has an attribute .tables
which is a dictionary of Table
objects describing everything web.database knows about the tables. Each Table
object is made up of Column
objects containing field information and converters for each field.
After a SELECT
statement the cursor attribute .info
contains a list of Column
objects for the columns selected to provide all the information available about those columns as well as conversion methods.
If the user needs to access the underlying DB-API driver using its own SQL dialect instead of the portable web.database one he can do so easily in two ways:
cursor.execute("select name from testTable where name = 'James'", mode='direct') cursor.baseCursor.execute("select name from testTable where name = 'James'")
All the methods and objects have similar functionality to allow the user access to the underlying driver.
The use of an object relational mapper in web.database.object means forms can be automatically generated to provide data access.