This tutorial explains how we can connect to a Microsoft SQL Server database from Python running under Linux or Windows using pyodbc library.
Pyodbc is an open source Python module that makes accessing ODBC databases simple. It implements the DB API 2.0 specification. Using it, we can easily connect Python applications to data sources with an ODBC driver.
The implementation explained here is straightforward.
In this tutorial, we'll use Steem SQL instance. Details are mentioned below :
The easiest method to install pyodbc is by using pip. Use below command to install pyodbc library.
pip install pyodbc
driver thats allows applications to talk to the MSSQL DB.driver manager.epel repository. For CentOS 7, it is available at http://mirror.vbctv.in/epel/7/x86_64/e/epel-release-7-9.noarch.rpmrpm -Uvh http://mirror.vbctv.in/epel//7/x86_64/e/epel-release-7-9.noarch.rpm
yum install -y unixODBC unixODBC-devel freetds
We can connect to SQL server with or without Data Source Name (DSN). Both the methods are mentioned below.
steemsqlserver.[steemsqlserver]
host = sql.steemsql.com
port = 1433
tds version = 7.0
tsql -S steemsqlserver -U steemit -P steemit
rohan).select name from DBSteem.dbo.Accounts where name like 'rohan%'goIf everything works fine, it will print the result of the query.
odbcinst -j to know where the configuration files are located. We need file location for drivers and system data source. In CentOS they are /etc/odbcinst.ini and /etc/odbc.ini respectively. However, the output of the command will give the file location.!
If the Driver and Setup does not work then search the libtds files using find command.
pyodbcpyodbc.connect('DSN='steemsqlserverdatasource'; UID='steemit'; PWD=''steemit; DATABASE='DBSteem';'
Example : Below code connects to the Steem SQL server and list all accounts which starts with 'rohan'.
Code Output
In this case, we specify the driver, SQL server name and ports and TDS Version in the pyodbc connection string.
pyodbc.connect('Driver='FreeTDS'; Server='sql.steemsql.com'; UID='steemit'; PWD='steemit'; Database='DBSteem'; TDS_Version='7.0'; Port='1433';')
Code Output
https://www.microsoft.com/en-us/download/details.aspx?id=53339
pyodbc.connect('Driver={ODBC Driver 13 for SQL Server}; Server=sql.steemsql.com; UID=steemit; PWD=steemit; Database=DBSteem;')
We saw how easily we can connect to Microsoft SQL server from CentOS or Windows using Python's pyodbc library.
If you have any questions or comments , I'd would love to hear from you in comment section.