What's causing 'unable to connect to data source' for pyodbc?

前端 未结 13 2115
北荒
北荒 2020-12-28 14:34

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          


        
相关标签:
13条回答
  • 2020-12-28 15:13

    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.

    0 讨论(0)
  • 2020-12-28 15:17

    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)
    
    0 讨论(0)
  • 2020-12-28 15:18

    I try with:

    • MS SQL 2008 Datacenter
    • Ubuntu 12.04 TLS (amd64)
    • Python 2.7

    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
    
    0 讨论(0)
  • 2020-12-28 15:18

    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.

    0 讨论(0)
  • 2020-12-28 15:19

    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!

    0 讨论(0)
  • 2020-12-28 15:19

    You can also set an environmental variable in your python script:

    os.environ['TDSVER'] = '8.0'
    
    0 讨论(0)
提交回复
热议问题