[DB-SIG] Persistent Database Connections

Andy Dustman andy@dustman.net
Mon, 13 Aug 2001 10:37:18 -0400 (EDT)


On Thu, 9 Aug 2001, Stanton Schell wrote:

> Is there any good documentation on how to create and use persistent db
> connections (in imported modules, etc.)?  I am using MySQL (3.23.36) and
> Py2.1.1.  All the documentation I have found on persistence only deals with
> persistent data.  I am fairly in the dark (newbie), so even a couple lines
> explaining how to easily pass a connection from one area of my program to
> another will help...

For MySQLdb (and in general for DB API databases):

db = MySQLdb.connect(...)

db is a database Connection object which may be passed around as needed.
To perform queries, you need a Cursor object:

c = db.cursor()

Queries are performed with execute():

c.execute(query_string, optional_sequence_of_parameters)

Results, if any, can be returned by the various fetchXXX() methods:

row = c.fetchone()
rows = c.fetchmany(n) # n optional
all_rows = c.fetchall()

A row is usually a tuple of column values, or None if no more are
available. Methods returning a sequence of rows return an empty sequence
if no more are available.

db.commit() # or rollback

should be obvious, though not usually needed or useful for MySQL.

-- 
Andy Dustman         PGP: 0xC72F3F1D
    @       .net     http://dustman.net/andy
I'll give spammers one bite of the apple, but they'll
have to guess which bite has the razor blade in it.