---
title: "Connect to SQL Server from Linux with ODBC"
description: "Set up an ODBC connection to run queries on a Microsoft SQL Server from Linux in this step-by-step guide."
canonical: "https://adamtheautomator.com/connect-to-sql-server-from-linux/"
---

# Connect to SQL Server from Linux with ODBC

> Set up an ODBC connection to run queries on a Microsoft SQL Server from Linux in this step-by-step guide.

Source: https://adamtheautomator.com/connect-to-sql-server-from-linux/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Connect to SQL Server from Linux with ODBC](https://adamtheautomator.com/wp-content/uploads/2019/08/tux-158547_1280.png)

# Connect to SQL Server from Linux with ODBC

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)1 August 20193 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Linux](/tag/linux/)[Microsoft SQL Server](/tag/microsoft-sql-server/)[Python](/tag/python/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Summary](#summary)

In a perfect database administrator world, everything would be the same. All servers would be identical and run the same workloads. They’re easier to manage. But, that’s not the case. Nowadays, System administrators have to manage different environments. This couldn’t be more evident in need to perform SQL queries from a Linux machine. In this post, you’ll learn how to connect to SQL Server from Linux!

Not a reader? Watch this related video tutorial!

**_Not seeing the video? Make sure your ad blocker is disabled._**

One way to connect to SQL Server from Linux is to use a Python module. But before you get that far, let’s first cover what environment I’m working with.

In this article, I’ll be demonstrating this task using Ubuntu 16.04 and I’ll be connecting to SQL Server 2012 R2. But, the same technique should apply to other Linux flavors and SQL Server versions as well. Database administrators rejoice!

## Prerequisites

To get started, you’re going to need to install a few prerequisites. First, since you’ll be connecting to a SQL Server instance from Python, you’ll need a Python module. A common Python module to connect to SQL is called [PyODBC](https://github.com/mkleehammer/pyodbc). This module allows you to query SQL databases via ODBC via a SQL Server ODBC driver for Linux. To get the latest version installed, use _pip_ (the Python package manager).

```bash
> sudo pip install pyodbc
```

If this does not work, you might not have pip installed. To install pip:

```bash
> sudo easy_install pip
```

Next, you need to create a Python script. I’m going to call this one _sql\_server.py_. To create a Python script, first create a blank file.

```bash
> touch sql_server.py
```

Then, using your editor of choice, add the below lines. The shebang followed by the path to the Python binary tells the interpreter this is a Python script. The `import` statement then allows you to call the library methods inside of the pyodbc module. Save this script.

```python
!/usr/bin/python
import pyodbc
```

Once you have the Python script created, run the script:

```bash
> python sql_server.py
```

If this runs without error, the pyodbc module has been installed successfully.

Next, add the code to execute a test query. To do this, create an ODBC string.

> _To learn more about crafting ODBC strings, [here](https://www.connectionstrings.com/odbc-dsn/)‘s a good resource._

The ODBC string is picky about what’s included. It took some time to figure out how to make this work but here’s what mine looks like. Below I’m passing the ODBC string as an argument to the `connect()` method that’s included with the _pyodbc_ module.

```python
conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=server.domain.local;PORT=1433;UID=DOMAIN\user;PWD=mypassword;DATABASE=mydatabasename;UseNTLMv2=yes;TDS_Version=8.0;Trusted_Domain=domain.local;')
```

Most of the ODBC string is evident, but one important fact is the double backslash for the _UID_. Always ensure that you’ve escaped any backslashes in the ODBC string. Also, some of the options I’m using are optional.

Also, you can either use the hostname for `SERVER` as I’ve done above or you can use the SQL Server IP address.

Feel free to add or remove them as you see fit to match your SQL Server.

Next, you need to create a cursor object that will allow you to pass a T-SQL statement to. This is done with the `cursor()` method.

```python
cursor = conn.cursor()
```

Now you have an object with an `execute()` method that can be used to pass any T-SQL statement we’d like into as shown below. This creates a `rows` variable containing the resulting dataset.

```python
cursor.execute("SELECT * FROM <tablename>")
rows = cursor.fetchall()
```

You’re now to the point where you’ll need to decide what to do with the dataset. You can send the results to a CSV file, put the results into another database or write the contents to the console.

Below, I’m printing the results to the console if the dataset is populated.

```python
if rows:
    print(rows)
```

![Printing SQL rows in Python](/wp-content/uploads/2019/07/Picture1-11.png)

Printing SQL rows in Python

You can see that if the dataset is printed out to the console, the output isn’t too pretty. At this point, it’s up to you to decide how to format or parse the data from the database. The hard part is over!

You’ll now end up with a script that looks like this:

```python
!/usr/bin/python
import pyodbc

conn = pyodbc.connect('DRIVER={FreeTDS};SERVER=server.domain.local;PORT=1433;UID=DOMAIN\user;PWD=mypassword;DATABASE=mydatabasename;UseNTLMv2=yes;TDS_Version=8.0;Trusted_Domain=domain.local;')

cursor.execute("SELECT * FROM <tablename>")
rows = cursor.fetchall()

if rows:
    print(rows)
```

## Summary

In this blog post, you learned how to use the _pyodbc_ Python module on Linux to connect to a SQL Server data source. The hardest part for me was figuring out the ODBC string but once you get that covered, you should be smooth sailing.

Once you’re connecting from Linux, why not see if you can up the performance [using performance counters](https://adamtheautomator.com/sql-server-performance-monitor/)?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fconnect-to-sql-server-from-linux%2F&text=Connect%20to%20SQL%20Server%20from%20Linux%20with%20ODBC)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fconnect-to-sql-server-from-linux%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fconnect-to-sql-server-from-linux%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2024/03/mssql-linux.jpg)

### [How to Install Microsoft SQL Server on Linux](/mssql-linux/)

Unlock the potential of Microsoft SQL (MSSQL) on Linux systems in solving database management challenges effortlessly!

![](https://adamtheautomator.com/wp-content/uploads/2021/12/Creating-Statistical-Plots-with-the-Seaborn-Python-Library.jpg)

### [Creating Statistical Plots with the Seaborn Python Library](/seaborn-python/)

Are you still using Excel to generate statistical plots? Perhaps it’s time to ditch it and switch to the Seaborn Python library to create many beautiful plots.

![](https://adamtheautomator.com/wp-content/uploads/2019/06/query-wmi-linux-python-python.png)

### [Python WMI: Query WMI on Remote Computers with Linux](/python-wmi/)

Learn to use Python for querying WMI on remote computers from a Linux system, such as Ubuntu.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
