pymssql: Connection to the database only works sometimes

不羁的心 提交于 2019-11-26 23:24:00

问题


I'm trying to connect to Azure SQL server using Python's pymssql. The problem is that the following script works but only sometimes, the other times I get this error:

_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed\n')

This is the script I'm using:

import pymssql
conn = pymssql.connect(server='x', user='x', password='x', database='x')
cursor = conn.cursor()
cursor.execute('SELECT * FROM customers');
row = cursor.fetchone()
while row:
    print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]))
    row = cursor.fetchone()

It would help me greatly if someone can tell me why this above script works only sometimes and rest of the times I get the "Adaptive Server connection failed" error.


回答1:


I reviewed these SO old threads Read from the server failed when trying to connect to sql-azure from tsql and What is TDS Protocol Version 8.0 and why should I use it?. The issue seems to be caused by using the wrong version of FreeTDS.

I found the key at the page of FreeTDS offical website http://www.freetds.org/faq.html#Does.FreeTDS.support.Microsoft.servers.

There is a table of versions of the TDS protocol by product http://www.freetds.org/userguide/choosingtdsprotocol.htm.

FreeTDS will alias this version to 7.1 for backwards compatibility reasons, but this should be avoided due to future compatibility concerns. See note below on obsolete versions.

If you use pymssql with FreeTDS on linux, I think you need to check the configuration file "freetds.conf" at the path /etc/freetds/.

This is my configuration for Azure SQL Server below:

# A typical Microsoft server
[egServer70]
        host = <database_name>.database.windows.net
        port = 1433
        tds version = 7.3

You can try to test the connection to Azure SQL server by using freetds tool 'tsql' to command 'tsql -H <database_name>.database.windows.net -U Username -D DatabaseName -p 1433 -P Password' .

Best Regards.



来源:https://stackoverflow.com/questions/32380367/pymssql-connection-to-the-database-only-works-sometimes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!