1.5.2.1 Full Code Listing

Here is a complete code listing so that you can experiment:

#!/usr/bin/env python

import sys; sys.path.append('../../../') # show python where the modules are

import web.database, web.database.object
connection = web.database.connect(
    adapter="snakesql", 
    database="database-object-simple",
    autoCreate = 1,
)
cursor = connection.cursor()

person = web.database.object.Table("Person")
person.addColumn(web.database.object.String(name="firstName"))
person.addColumn(web.database.object.String(name="surname"))

database = web.database.object.Database()
database.addTable(person)
database.init(cursor)

if not database.tablesExist():
    database.createTables()
    print "Created Table"

john = database['Person'].insert(firstName="John", surname="Smith")
print john['firstName']
print john['surname']

john['surname'] = 'Doe'
print john['surname']

print john['rowid']

row1 = database['Person'][1]
row2 = database['Person'].row(1)
print row1 == row2 == john

connection.close() # Close the connection without saving changes

The output is:

Created Table
John
Smith
Doe
1
1

Note: If you run the code more than once you will be adding lots of John Smiths to the test database and so the rowid value will be one larger each time you run the code. After the first time you run the code the line Created Table will not be output since the table will already be created.