MSSQL in python 2.7

If you're coming across this question through a web search, note that pymssql nowadays does support Python 2.7 (and 3.3) or newer. No need to use ODBC.

From the pymssql requirements:

Python 2.x: 2.6 or newer. Python 3.x: 3.3 or newer.

See http://pymssql.org/.


You can also use pyodbc to connect to MSSQL from Python.

An example from the documentation:

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
    print row.user_id, row.user_name

The SQLAlchemy library (mentioned in another answer), uses pyodbc to connect to MSSQL databases (it tries various libraries, but pyodbc is the preferred one). Example code using sqlalchemy:

from sqlalchemy import create_engine
engine = create_engine("mssql://me:pass@localhost/testdb")
for row in engine.execute("select user_id, user_name from users"):
    print row.user_id, row.user_name