簡體   English   中英

使用 Python 訪問 SQL 服務器 SQL 數據庫在 Z3A580F1422089677F13ZF3 上給出錯誤

[英]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()

參考: 創建(Python)代碼來查詢您的數據庫

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM