使用 Python 访问 Azure 上的 SQL Server SQL 数据库会出错



我正在尝试使用Python中的pymssql模块来访问SQL Server SQL数据库。但是,当我在 Ubuntu Linux 上运行我的代码时,我的代码会给出回溯错误。顺便说一句,该系统实际上是一个Microsoft的Azure VM。

下面是我的代码:

import pymssql
connection1 = pymssql.connect(
server = 'redworth-test-sql.database.windows.net',
user = '*********@redworth-test-sql',
password = '**********',
database = 'redworth-test-sql-database'
)
sql = connection1.cursor()
cursor.execute('insert into table1 values ('Rohit', 'Karthik', '2006/08/02')')
allRows = sql.fetchall()
print(allRows)
connection1.close()

(出于安全原因,我使用*作为我的用户名和密码,但我计算机上的代码具有实际字符串(

(我也使用 pip 在 python3 上安装了我的 pymssql 模块(

但是运行该代码会在我的系统上给我以下错误:

Traceback (most recent call last):
File "src/pymssql.pyx", line 636, in pymssql.connect
File "src/_mssql.pyx", line 1957, in _mssql.connect
File "src/_mssql.pyx", line 676, in _mssql.MSSQLConnection.__init__
File "src/_mssql.pyx", line 1683, in _mssql.maybe_raise_MSSQLDatabaseException
_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:nAdaptive Server connection failed (redworth-test-sql.database.windows.net:1433)n')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyMsSQL.py", line 7, in <module>
database = 'redworth-test-sql-database'
File "src/pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:nAdaptive Server connection failed (redworth-test-sql.database.windows.net:1433)n')

我不确定是什么导致了此错误。

提前感谢您的帮助。

恭喜你,pyodbc适合你。

Azure文档都建议我们使用pyodbc连接到 Azure SQL 数据库,下面是示例:

import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

参考:创建(Python(代码来查询您的数据库。

希望这有帮助。

最新更新