使用Python通过Windows身份验证连接到MS SQL Server?

问题描述 投票:39回答:3

如何使用Windows身份验证将MS SQL Server与pyodbc库连接?

我可以通过MS Access和SQL Server Management Studio连接,但无法获得Python的工作连接ODBC字符串。

这是我尝试过的(也没有'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]')
sql-server sql-server-2008-r2 odbc windows-authentication pyodbc
3个回答
55
投票

您可以将连接字符串指定为一个使用分号(;)作为参数分隔符的长字符串。

工作范例:

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()

对于具有大量参数的连接字符串,以下内容将以相似的方式完成相同的操作:

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

(请注意,各个字符串组件之间没有逗号。)


20
投票

也可以使用关键字指定Windows身份验证。在功能上与接受的答案没有什么不同,我认为它使代码格式化更容易:

cnxn = connect(driver='{SQL Server}', server='localhost', database='test',               
               trusted_connection='yes')

0
投票

只是想添加一些东西,因为我在这里看到使用localhost的解决方案;根据我的经验,SQL Server存在此问题,不确定它是ODBC驱动程序还是服务itse,如果您不想指定本地计算机名,则更喜欢使用(本地)。

cnxn = connect(driver='{SQL Server}', server='(local)', database='test',               
               trusted_connection='yes')
© www.soinside.com 2019 - 2024. All rights reserved.