11.1. Basic Connectivity
The Python APIs are likely the simplest database APIs of any in this
book. As with the other APIs, we need to start with database
connectivity -- making the connection. Because Python has an
interactive interface, the simplest way to demonstrate a connection
is by using the command line interpreter. The following two Python
sessions demonstrate simple database connections to MySQL and mSQL,
respectively. The first example shows MySQL connectivity:
[4:30pm] athens> python
Python 1.5.1 (#1, Jun 13 1998, 22:38:15) [GCC 2.7.2] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import MySQL;
>>> db = MySQL.connect('athens.imaginary.com');
>>> db.selectdb('db_test');
>>> result = db.do('select test_val from test where test_id = 1');
>>> print result;
[['This is a MySQL test.']]
>>>
The mSQL code that does the same thing looks nearly identical:
[4:30pm] athens> python
Python 1.5.1 (#1, Jun 13 1998, 22:38:15) [GCC 2.7.2] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import mSQL;
>>> db = mSQL.connect('athens.imaginary.com');
>>> db.selectdb('db_test');
>>> result = db.query('select test_val from test where test_id = 1');
>>> print result;
[('This is a mSQL test.',)]
>>>
The connect() call for both APIs is similar,
though not identical. In the previous MySQL session, we are
connecting to a database that allows global access. Because no user
name or password is required, the connect() call
for the MySQL session looks similar to the call for the mSQL session.
You can, however, specify user name and password arguments when
required by your MySQL database. For example, db =
MySQL.connect('athens.imaginary.com',
'myuid',
'password'); will
connect you to the MySQL server at
athens.imaginary.com as the user
"myuid" using the password "password."
Neither API even requires a host name if you are connecting to the
local machine. In such situations, they are smart enough to use a
Unix domain socket (on Unix systems) for quicker connectivity.