使用pyodbc将SQL Server连接到Python 3

时间:2022-06-07 11:49:55
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. My codes gave a error:

我尝试使用python 3与模块pyodbc连接SQL Server Express。我的代码出错了:

('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]命名管道提供程序:无法打开与SQL Server的连接[2]。(2)(SQLDriverConnect)')

Any idea for this?

对此有何想法?

1 个解决方案

#1


0  

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!

请注意,端口号以逗号分隔!

#1


0  

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!

请注意,端口号以逗号分隔!