Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

python - pymssql: Connection to the database only works sometimes

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: Adaptive Server connection failed ')

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...