python连接sql server数据库windows认证_使用Python使用Windows身份验证连接到MS SQL Server吗?...

使用Python的pyodbc库通过Windows身份验证连接到MS SQL Server的方法。尝试了多种连接字符串,最终找到了有效解决方案:将连接字符串作为包含分号(;)分隔参数的长字符串。提供了一个工作示例代码,展示了如何建立连接并执行查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How do I connect MS SQL Server using Windows Authentication, with the pyodbc library?

I can connect via MS Access and SQL Server Management Studio, but cannot get a working connection ODBC string for Python.

Here's what I've tried (also without 'Trusted_Connection=yes'):

pyodbc.connect('Trusted_Connection=yes',

driver='{SQL Server}', server='[system_name]',

database='[databasename]')

pyodbc.connect('Trusted_Connection=yes', uid='me',

driver='{SQL Server}', server='localhost',

database='[databasename]')

pyodbc.connect('Trusted_Connection=yes',

driver='{SQL Server}', server='localhost',

uid='me', pwd='[windows_pass]', database='[database_name]')

pyodbc.connect('Trusted_Connection=yes',

driver='{SQL Server}', server='localhost',

database='[server_name]\\[database_name]')

pyodbc.connect('Trusted_Connection=yes',

driver='{SQL Server}', server='localhost',

database='[server_name]\[database_name]')

pyodbc.connect('Trusted_Connection=yes',

driver='{SQL Server}',

database='[server_name]\[database_name]')

解决方案

You can specify the connection string as one long string that uses semi-colons (;) as the argument separator.

Working example:

import pyodbc

cnxn = pyodbc.connect(r'Driver={SQL Server};Server=.\SQLEXPRESS;Database=myDB;Trusted_Connection=yes;')

cursor = cnxn.cursor()

cursor.execute("SELECT LastName FROM myContacts")

while 1:

row = cursor.fetchone()

if not row:

break

print(row.LastName)

cnxn.close()

For connection strings with lots of parameters, the following will accomplish the same thing but in a somewhat more readable way:

conn_str = (

r'Driver={SQL Server};'

r'Server=.\SQLEXPRESS;'

r'Database=myDB;'

r'Trusted_Connection=yes;'

)

cnxn = pyodbc.connect(conn_str)

(Note that there are no commas between the individual string components.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值