使用 Python 访问 Azure 上的 SQL 服务器 SQL 数据库出现错误

Using Python to access SQL Server SQL Database on Azure Gives an Error

我正在尝试使用 Python 中的 pymssql 模块来访问 SQL 服务器 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()

参考:Create(Python) code to query your database.

希望对您有所帮助。