Accessing SQL Server from Python

So, I am working on a Python Programming Certificate and had to spend a bit of time working with MySQL. But I was wishing I could learn how to acess SQL Server from Python. Turns out that’s pretty straight forward:

import pyodbc

server = "myserver"
driver = "SQL Server"
database = "mydatabase"

connStr = "DRIVER={%s};SERVER=%s;DATABASE=%s;Trusted_Connection=yes"%(driver,server,database)
conn = pyodbc.connect(connStr)
dbCursor = conn.cursor
query = "SELECT * FROM sys.tables"
dbCursor.execute(query)
for table in dbCursor:
     print table[0]

That brings up a list of all the table names in mydatabase and prints it to the screen. Time to work more with SQL Server in Python.

You can download pyodbc from http://code.google.com/p/pyodbc/.

Advertisements

Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s