|
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_nameSelect 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_nameGet 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_countA 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' % countSupply parameters: cursor.execute("select count(*) as user_count from users where age > ?", 21)
row = cursor.fetchone()
print '%d users' % row.user_countDelete 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.rowcountUse triple-quotes with a longer SQL statement: cursor.execute("""
select user_id, user_name
from users
where last_logon < ?
and bill_overdue='y'
""", cutoff)
|
Sign in to add a comment
Nice start
Very helpful! Thank you.
Very very very nice ! I need to access a lot of mdb, so i really need your library. Great job !