My favorites | Sign in
Project Logo
             
Search
for
Updated May 24, 2009 by mkleehammer
Labels: Featured
GettingStarted  
Quick Examples To Get You Started

Make a direct connection to a database and create a cursor:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()

Select some values and print them:

cursor.execute("select user_id, user_name from users")
for row in cursor:
    print row.user_id, row.user_name

Select the values, but use a more compact form. The execute function returns the cursor object, so execute can be moved into the for loop:

for row in cursor.execute("select user_id, user_name from users"):
    print row.user_id, row.user_name

Get all the rows at once using fetchall, freeing up the cursor:

rows = cursor.execute("select user_id, user_name from users").fetchall()

Select a calculated value, giving it a name:

cursor.execute("select count(*) as user_count from users")
row = cursor.fetchone()
print '%s users' % row.user_count

A shorter version of the previous. The execute method returns the cursor, so we can call fetchone on the return value. We are only selecting one column, so we know it is column zero and we don't need to name the column:

count = cursor.execute("select count(*) from users").fetchone()[0]
print '%s users' % count

Supply parameters:

cursor.execute("select count(*) as user_count from users where age > ?", 21)
row = cursor.fetchone()
print '%d users' % row.user_count

Delete some records and retrieve the count:

cursor.execute("delete from users where age < ?", 18)
cnxn.commit() # don't forget this!
print "deleted %s users" % cursor.rowcount

Use triple-quotes with a longer SQL statement:

cursor.execute("""
               select user_id, user_name
                 from users
                where last_logon < ?
                  and bill_overdue='y'
               """, cutoff)

Comment by ratuliut, Sep 26, 2009

Nice start

Comment by karen.hensley, Oct 29, 2009

Very helpful! Thank you.

Comment by prah...@gmail.com, Nov 12, 2009

Very very very nice ! I need to access a lot of mdb, so i really need your library. Great job !


Sign in to add a comment
Hosted by Google Code