I\'m trying to connect to an MSSQL database from python on Linux (SLES).
I have installed pyodbc and Free TDS. From the command line:
tsql -H server
I found my way here after an Ubuntu 18.04 upgrade broke my pyodbc connections. Turns out, in my //etc/odbcinst.ini file my driver description order was switched around.
So when I called:
from pyodbc import connect,drivers
conn = connect(driver=drivers()[0], ...
I should have been calling:
conn = connect(driver=drivers()[1], ...
In other words, I was calling the wrong driver because of a simple index issue. Hope this helps someone else.
The follow worked for me:
Modify python2.7/site-packages/sql_server/pyodbc/base.py
def get_new_connection(self, conn_params):
...
- cstr_parts['SERVERNAME'] = host
+ cstr_parts['SERVER'] = host
+ cstr_parts['PORT'] = str(port)
I try with:
And this works for me:
Test connection:
tsql -H 10.19.4.42 -p 1433 -U DAVIDG -P 123456
on /etc/odbcinst.ini add:
[ODBC]
Trace = Yes
TraceFile = /tmp/odbc.log
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
UsageCount = 1
on /etc/odbc.ini add:
[SQLDemo]
Description=my dsn
Driver=FreeTDS
Database=teste3
Servername=SQLDemo
on /etc/freetds/freetds.conf add:
[SQLDemo]
host = 10.19.4.42
port = 1433
tds version = 8.0
test with test.py:
#!/usr/bin/python
import pyodbc
cnx = pyodbc.connect("DSN=SQLDemo;UID=DAVIDG;PWD=123456")
cursor = cnx.cursor()
cursor.execute("select * from Company;")
for row in cursor:
print row.Name
In my case my host files are missing when i ping to that server it was not pinging. Then i noticed my host files are missing by applying sudo vi /etc/hosts command in the terminal. I added my host and ip address and worked fine for me.
I was also having problems with this after upgrading my version of ubuntu to 12.04. My old freetds config /etc/freetds/freetds.conf
was no being found so I had to move it to /usr/local/etc
at which point it started working again.
Also my driver location is /usr/local/lib/libtdsodbc.so
Hope this helps save someone a day and a half!
You can also set an environmental variable in your python script:
os.environ['TDSVER'] = '8.0'