使用 pyodbc 将 SQL Server 连接到 Python 3 [英] Connect SQL Server to Python 3 with pyodbc

查看:77
本文介绍了使用 pyodbc 将 SQL Server 连接到 Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

我尝试使用带有模块 pyodbc 的 python 3 来连接 SQL Server Express.我的代码出错了:

I try using python 3 with module pyodbc to connect SQL Server Express. My codes gave a error:

('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]命名管道提供程序:无法打开与 SQL Server [2] 的连接.(2)(SQLDriverConnect)')

('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect)')

对此有什么想法吗?

推荐答案

这是一个使用 Trusted_Connection=yes 对我有用的示例

Here is an example that worked for me using 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!

这篇关于使用 pyodbc 将 SQL Server 连接到 Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆