pymssql on Windows can connect to local SQL Server but not to Azure SQL

空扰寡人 提交于 2019-12-13 15:54:38

问题


Trying to connect to an Azure SQL DB (v12) using pymssql, I am able to connect query and write to my local MSSQL instance using pymssql.

I am getting an "Adaptive Server connection failed" failed error and my research seems to point to FreeTDS, but I have not installed FreeTDS on my machine.

Using the tsql utility, i am able to connect to the Azure SQL instance

Why would I fail to connect using pymssql?

pymssql connection string

import pymssql
conn = pymssql.connect(server='<severname>.database.windows.net',user='mickey@in4live', password='<pass>', database='tesdb')
cursor = conn.cursor()
cursor.execute("select 1")

Outputs

conn = pymssql.connect(server='.database.windows.net',user='mickey@', database='tesdb') File "pymssql.pyx", line 641, in pymssql.connect (pymssql.c:10824) pymssql.OperationalError: (20002, 'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (:1433)\n'

However

tsql -H <servername>.database.windows.net -p 1433 -U mickey@<servername> -P <pass>

Connects successfully


回答1:


The default Windows builds of pymssql that get installed using pip install pymssql are statically linked to FreeTDS, so the pymssql binaries (.pyd files) include the required FreeTDS components to establish unencrypted connections. This is sufficient for connecting to many (most?) local SQL Server installs where secure connections are not required.

However, all connections to Azure SQL Database require encryption (ref: here), so a basic pip install pymssql on Windows will not be able to connect to an Azure SQL database. Instead, we need to install pymssql with SSL support as described in the following MSDN article

Step 1: Configure development environment for pymssql Python development

where "Step 1" refers to the first step in Microsoft's tutorial for Azure

Connect to SQL Database by using Python




回答2:


@Wasky, I also recommend you use pyodbc instead of pymssql. The latest version of pymssql on Windows has some issues with ssl that cause ssl linking issues.

Step 1: Install the Microsoft ODBC Driver 11, 13 or 13.1: https://www.microsoft.com/en-us/download/details.aspx?id=50420

Step 2: Install pyodbc

> cd C:\Python27\Scripts>  
> pip install pyodbc 

Step 3: Run your sample

import pyodbc 
server = 'tcp:myserver.database.windows.net' 
database = 'mydb' 
username = 'myusername' 
password = 'mypassword' 
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

Let me know how this goes.



来源:https://stackoverflow.com/questions/39040536/pymssql-on-windows-can-connect-to-local-sql-server-but-not-to-azure-sql

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