Connecting to a Microsoft SQL Server database from Python under Ubuntu

Free tools are great, but the world ain’t all sunshine and rainbows. Sometimes, we may need to connect to a Microsoft SQL Server database from one of our Python applications running under Linux. Fortunately, there are ways to achieve this.

I am assuming we got this:

  • • A Microsoft SQL Server installation running under Windows. I tested this using Microsoft SQL Server 2008 R2 Express, but hopefully this will work with other versions as well.
  • Ubuntu Linux. I am using 12.04 LTS.

Without further ado, here are the steps you should follow to get this working.

1. SQL Server setup

Your SQL Server installation must be setup to allow external connections. If the DB is not administered by you this might not be a problem, but in case you do have administrator level access and need to do it yourself, read here.

Now you must have setup a port in which SQL Server is listening. Remember it.

Make sure you are not blocked by Windows firewall or such when you attempt to connect to the Windows computer. Attempting a telnet will help us check if there are connection problems. For example, try running telnet <sqlserverpc> <port> from Ubuntu and check the connection doesn’t fail.

Regarding authentication, I have only tried this with the sa login enabled (ie. not using Windows Authentication). You may read on how to do that here.

2. Install required packages under Ubuntu

These are the things we are going to need:

  • FreeTDS is is a set of libraries that allows programs to natively talk to Microsoft SQL Server databases. It’s what we usually call a driver.
  • UnixODBC acts as a driver manager and is the implementation of the ODBC API.
  • pyodbc is a Python 2.x and 3.x module that allows you to use ODBC to connect to almost any database.

From a terminal, run:

sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc

From the Virtualenv of our Python application (if you are not using one, you should!) run pip install pyodbc.

3. Setup server in FreeTDS’s settings

Edit the file /etc/freetds/freetds.conf and replace placeholders appropriately. Note that we are calling our server sqlserver.

    host = <ip address of the computer running SQL Server>
    port = <port>
    tds version = 7.0

After this you can test the connection with this command:

tsql -S sqlserver -U <username> -P <password>

Then run some SQL Server command to make sure everything works fine. For example you may run a DB query like this:

select * from <database name>.dbo.<table name>

If it worked, it will print the results of the query. Quit with Ctrl+D.

4. Setup unixODBC to use FreeTSD & add a data source

First, run odbcinst -j to know where our configuration files are located. We will need to edit two files: the “drivers” and “system data source”. I assume they are /etc/odbcinst.ini and /etc/odbc.ini respectively, but the output of the command will tell you this.

Edit /etc/odbcinst.ini like this:

Description = TDS driver (Sybase/MS SQL)
# Some installations may differ in the paths
#Driver = /usr/lib/odbc/
#Setup = /usr/lib/odbc/
Driver = /usr/lib/x86_64-linux-gnu/odbc/
Setup = /usr/lib/x86_64-linux-gnu/odbc/
CPTimeout =
CPReuse =
FileUsage = 1

If the paths for Driver and Setup do not work in your installation, you can find where these files are located by running find / -name “libtds*”.

Edit /etc/odbc.ini like this, to add a data source named sqlserverdatasource:

Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = sqlserver
Database = <name of your database>

Now you may test the connection to out data source works by running isql -v sqlserverdatasource <username> <password>.

5. Connect to our data source from a Python application

If everything is fine, with the help of pyodbc it should be really easy! You may try the following snippet:

import pyodbc

dsn = 'sqlserverdatasource'
user = '<username>'
password = '<password>'
database = '<dbname>'

con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
cnxn = pyodbc.connect(con_string)

That should be it :-)

We are Tryolabs. A boutique hi-tech company that crafts amazing Internet, Machine Learning & Mobile products.

23 thoughts on “Connecting to a Microsoft SQL Server database from Python under Ubuntu

  1. Excellent! You've made this real easy.
    I'd recommend using locate rather than find to locate the ftds libs, mine ended up in /usr/lib/odbc/

    Thank you

  2. Alan, I've followed your tut religiously and I still obtain this error:

    pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')

    I've falled stumped, any clues?

  3. You, sir, are a genius, Thanks! Hours have been saved here.

    It is interesting how you cannot insert the server details directly in the connection string using Python on Linux, and instead you have to create a DSN and reference that in the connection string… just not very user friendly imo!

  4. Regards, this is happening to me

    nelson@Nelson-Latitude:/etc/freetds$ tsql -S -U sa
    locale is "es_NI.UTF-8"
    locale charset is "UTF-8"
    using default charset "UTF-8"
    63Error 20009 (severity 9):
    Unable to connect: Adaptive Server is unavailable or does not exist
    OS error 110, "Expiró el tiempo de conexión"
    There was a problem connecting to the server

  5. Excuse me if English is not correct, but I'm using GoogleTranslate.

    Thank you for the information you have provided, it has served me. I did everything you mentioned, among other things further, however reports me the following error:

    locale is "es_PE.UTF-8"
    locale charset is "UTF-8"
    using default charset "UTF-8"
    Msg 18456 (severity 14, state 1) from PC-07 Line 1:
             "Login failed for user 'username'."
    Error 20002 (severity 9):
             Adaptive Server connection failed
    There was a problem connecting to the server

    I'm still looking on Google, but if you already know the solution to this incidence, I'd appreciate the proportions.


  6. Thanks for the great resource! I’m still having problems. I have multiple instances running on my server. How would I specify them for the tsql -S connection. Here are the results of tsql -LH rws

    root@dexter:/etc/freetds# tsql -LH rs11
    ServerName RS11
    InstanceName WASPDBEXPRESS
    IsClustered No
    Version 9.00.3042.00
    tcp 56297

    ServerName RS11
    InstanceName RWS
    IsClustered No
    Version 9.00.4035.00
    tcp 59614
    np \\RS11\pipe\MSSQL$RWS\sql\query


Leave a Reply

Your email address will not be published. Required fields are marked *