looking for ocbc example

M.-A. Lemburg mal at egenix.com
Fri Sep 21 15:20:00 CEST 2007

Carl K wrote:
> I am sure this is what I want:
> http://www.python.org/topics/database/docs.html
> "The documentation for the PythonWin ODBC module."
> but it is 404.
> google isn't being nice.
> Anyone know where I can find some simple examples?
> I have used odbc in other environments, so just need to know what modules, and 
> the lines to connect and execute a sql command.

Here's a very simple example for mxODBC:

# mxODBC is available from http://www.egenix.com/products/python/mxODBC/:

# On Windows:
from mx.ODBC import Windows as Database

# On Mac OS X:
from mx.ODBC import iODBC as Database

# On Linux/BSD/etc.:
from mx.ODBC import unixODBC as Database
# or
from mx.ODBC import iODBC as Database

# Open a connection to the database
connection = Database.DriverConnect('DSN=<datasourcename>;'
# replace the values accordingly, add new keyword-value pairs as
# necessary for your data source; data sources are configured
# in the ODBC manager

# Create a cursor; this is used to execute commands
cursor = connection.cursor()

# Create a table
cursor.execute('CREATE TABLE mxodbcexample1 '
               ' (id integer, name varchar(10), data varchar(254))')
# this command does not create a result set, so there's nothing
# to fetch from the database; however in order to make the
# change permanent, we need to commit the change

# Prepare some data rows to add to the table, ie. a list of tuples
rows = []
for i in range(42):
    name = 'name-%i' % i
    data = 'value-%i' % i
    rows.append((i, name, data))

# Add the data in one go; the values from the tuples get assigned
# to the ?-mark parameter markers in the SQL statement based on
# their position and the SQL statement is executed once for
# each tuple in the list of rows
cursor.executemany('INSERT INTO mxodbcexample1 VALUES (?,?,?)',

# If you apply changes to the database, be sure to commit or
# rollback your changes; a call to .commit() or .rollback()
# will implicitly start a new transaction

# Now fetch some data rows
from_id = 40
to_id = 42
cursor.execute('SELECT * FROM mxodbcexample1'
               ' WHERE (id >= ?) and (id < ?)',
               (from_id, to_id))

# Fetch the results
for i, row in enumerate(cursor.fetchall()):
    print 'Row %i: %r' % (i, row)

# Remove the table again
cursor.execute('DROP TABLE mxodbcexample1')

# Close the connection

With MS Access this gives:

Row 0: (40, 'name-40', 'value-40')
Row 1: (41, 'name-41', 'value-41')

Marc-Andre Lemburg

Professional Python Software directly from the Source
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::

More information about the Python-list mailing list