Tuesday, April 30, 2013

Connecting Python to SQL Server on OSx

After several hours and many frustrating errors, I was able to query SQL Server with Python. Previously, I went through several searches suggesting to install FreeTDS or find ODBC drivers. The steps were usually overly complicated and the instructions produced errors that send me down other tangents.

So here is it simply:
1.  Install pyodbc. (https://code.google.com/p/pyodbc/)
     Make sure the Python version and bit count (32 or 64) match your system.
2. Buy the driver from http://www.actualtech.com/
     I know, buy a driver? But it's $35 and I had it installed and running my test scripts in 5 minutes.
     Given my billable rate the client was happy to pay for it.
     If you're skeptical, you can install the driver for free with a few restrictions.

Here's a sample of my code:

import pyodbc

cnxn = pyodbc.connect('DRIVER={Actual SQL Server};SERVER=127.0.0.1;DATABASE=somedatabase;UID=username;PWD=password')
cursor = cnxn.cursor()

q = cursor.execute("select firstname, lastname from users")
row = cursor.fetchone()
if row:
    print(row)

No comments:

Post a Comment