XML technologies / XML / Python & XML / Python and distributed systems design / Creating the database
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
Describing the installation of a particular database is beyond this book’s scope. If databases are entirely new to you, however, we provide a brief overview of how this particular database was set up and used in this example. This overview applies broadly to all database systems, including SQL Server, Postgres and MySQL. As a Python-XML developer who glues applications together, you will benefit from understanding at least the basics of working with databases.
We used Microsoft SQL Server as the relational database when building this example. Only a simple table is created, however, and any database supporting SQL queries should suffice. An SQL script for creating tables is supplied and should work on any SQL platform. The Python connection code shown here uses ODBC. If you prefer another database to SQL Server, you may need to download a Python API to access it. The MySQLdb API, for example, is available at SourceForge: MySQL for Python and provides access to MySQL databases from Python. Regardless of your connection API, the SQL commands shown in this section should be identical.
Creating a profile database
After installing your chosen database system, your first task is to create a database in it. If you use SQL Server or your database offers an administration GUI, this may simply mean entering a database name in a dialog box. In SQL Server, for example, find the database directory in SQL Enterprise Manager. Right-click there and choose New Database. The database name should be Profiles. Without a GUI, the following simple SQL statement should suffice:
CREATE DATABASE Profiles Once ready, you may want to create and enable a user with read and write access to this database, but not to others. Consult your database documentation for details of creating specific user accounts. For this example, SQL Server user webuser was created with password w3bus3r. This authentication information is needed in the ODBC connection code.
Creating a customer table
After creating a database with a GUI or SQL statements, create a simple table named Customer. It contains some basic user information and serves as the sole location for customer information used by the different distributed applications. Its fields cover only the basics, but you could easily add other kinds of system-related information.
The table Customer can be created with a GUI in SQL Enterprise Manager for SQL Server, or in any database using this SQL code:
CREATE TABLE Customer (
firstname varchar (255) NULL,
lastname varchar (255) NULL,
address1 varchar (255) NULL,
address2 varchar (255) NULL,
city varchar (255) NULL,
state varchar (2) NULL,
zip varchar (10) NULL,
customerId varchar (40) NULL)This table is very simple. All data types are varchar and can easily be treated as strings and integers in Python. Note the differing field lengths in the Customer table. Most can contain between 0 and 256 characters. Others must meet restrictions, such as two characters for the state abbreviation and a limit of 10 digits for the postal code.
If you use SQL Server, remember to register your new database as an ODBC source on the machine running database clients. In this sample application, only the XML switch that loads the CustomerProfile class needs a database connection. To connect to SQL Server, use the ODBC manager in Windows Control Panel to select your database. Once this is done, the ODBC code presented here will work.
Populating the database
You can populate the fields of your new table with an SQL statement like this:
insert into Customer values('John',
'Smith',
'123 Evergreen Terrace',
'',
'Podunk',
'WA',
'98072',
'234-E838839')This statement creates a new table row with the corresponding values in quotation marks. To populate several rows, you can resort to good old data entry using the script popdb.py shown in the following example. This simple script just reads command-line input and inserts it into the database. It is intended for the ODBC module and SQL Server. If you use another database, you must adapt the connection code.
Example: popdb.py
"""
popdb.py - Füllen der Profile/Kunden-DB mittels ODBC-Aufrufen
"""
import dbi, odbc
conn = odbc.odbc("Profiles/webuser/w3bus3r")
cmd = conn.cursor()
# Schleife für die Eingabewerte
while 1:
firstname = raw_input("Vorname:")
lastname = raw_input("Nachname:")
address1 = raw_input("Adresse1:")
address2 = raw_input("Adresse2:")
city = raw_input("Ort:")
state = raw_input("Land, max. 2 Buchstaben:")
zip = raw_input("PLZ, max. 10 Ziffern:")
customerId = raw_input("Kunden-ID, max. 40 Zeichen:")
# Ausführen der SQL-Anweisung
cmd.execute("insert into Customer values('"
+ firstname + "', '"
+ lastname + "', '"
+ address1 + "', '"
+ address2 + "', '"
+ city + "', '"
+ state + "', '"
+ zip + "', '"
+ customerId + "')")
# Frage nach weiteren Einträgen
finished = raw_input("weiter? [j/n]:")
if (finished == "n"):
breakSince there is no error handling in popdb.py, violating a table constraint raises an exception and the row is not inserted.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de