简体   繁体   English

使用 pyodbc 将 SQL Server 连接到 Python 3

[英]Connect SQL Server to Python 3 with pyodbc

import pyodbc

cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER=LENOVO-PCN;DATABASE=testing;')

cursor = cnxn.cursor()

cursor.execute("select Sales from Store_Inf")
row = cursor.fetchone() 
if row: 
    print (row)

I try using python 3 with module pyodbc to connect SQL Server Express.我尝试使用带有模块 pyodbc 的 python 3 来连接 SQL Server Express。 My codes gave a error:我的代码给出了一个错误:

('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect)') ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: 无法打开到 SQL Server [2] 的连接。(2) (SQLDriverConnect)')

Any idea for this?对此有什么想法吗?

Here is an example that worked for me using Trusted_Connection=yes这是一个使用 Trusted_Connection=yes 对我有用的示例

import pyodbc

conn_str = pyodbc.connect(
    Trusted_Connection='Yes',
    Driver='{ODBC Driver 11 for SQL Server}',
    Server='SERVER_NAME,PORT_NUMBER',
    Database='DATABASE_NAME'
)

connection = pyodbc.connect(conn_str)

Please note that port number is comma separated!请注意端口号以逗号分隔!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM