简体   繁体   中英

Unable to connect SQL server via python from Linux machine

We are getting following error while connecting to SQL server from Linux machine.

('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified')

Can you please help me?

Here is code,

odbc.ini

[sqlserverdatasource]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = Name
Database = DatabaseName

--------------------
odbcinst.ini

[FreeTDS]
Description = TDS driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1

connection_string = 'DSN=sqlserverdatasource;DRIVER={FreeTDS}; SERVER=Name;PORT=1433;DATABASE=DatabaseName; UID=UserName; PWD=UserPassword;'

I would recommend you use the ODBC Driver.

Here is how you can install it:

Ubuntu 16.04

sudo su 
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
exit
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql unixodbc-dev

RHEL 7

sudo su
curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo
exit
sudo ACCEPT_EULA=Y yum install -y msodbcsql unixODBC-devel 

Once you install the driver you can create your odbc.ini as described above.

If you are using other Linux distros, check out this blog for more details: https://blogs.msdn.microsoft.com/sqlnativeclient/2017/02/04/odbc-driver-13-1-for-linux-released/

Here is a getting started guide if you are trying to use pyodbc: https://www.microsoft.com/en-us/sql-server/developer-get-started/python-ubuntu

Not sure if that will help, but you can try to install new Microsoft odbc driver for SQL Server: "msodbcsql"
More details are here: https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-tools

If you are working with python:

Try using pytds, it works throughout more complexity environment than pyodbc and more easier to setup.

I made it work on Ubuntu 18.04

Ref: https://github.com/denisenkom/pytds

Example code in documentation:

import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute("select 1")
        cur.fetchall()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM