无法使用Active Directory身份验证从python连接到SQL Server

时间:2016-10-18 21:34:00

标签: python sql-server

我正在使用pymssql库将python连接到Sql Server。我可以使用windows / sql server身份验证进行连接。我想使用Active Directory身份验证进行连接。

尝试以下连接字符串。但它失败了,错误:

unexpected keyword authentication


conn = pymssql.connect(server='adventureworks.database.windows.net', authentication = 'Active Directory Password',user='username@server.com',password='Enterpasswordhere', database='dbo')

2 个答案:

答案 0 :(得分:2)

如果您使用的是Windows计算机,则可以使用pyodbc 13.1和Microsoft登录助手执行此操作。

  1. 安装pyodbc
    https://www.microsoft.com/download/details.aspx?id=53339

  2. 安装登录助手
    http://go.microsoft.com/fwlink/?LinkId=234947

  3. 测试连接

    导入pyodbc
    server = 以windows.net结尾的服务器名称
    database = 数据库
    username = 用户名
    密码= 密码
    tablename = tablename

    driver ='{SQL Server的ODBC驱动程序13}' cnxn = pyodbc.connect('DRIVER ='+ driver +
                      '; PORT = 1433; SERVER ='+ server +
                      “; PORT = 1443; DATABASE =“+数据库+
                      '; UID =' +用户名+
                     '; PWD ='+密码+
                      '; Authentication = ActiveDirectoryPassword')

    cursor = cnxn.cursor()
    cursor.execute(“SELECT TOP 20 * from”+ tablename)
    row = cursor.fetchone()

    while row:

    print str(row [0])+“”+ str(row [1])
       row = cursor.fetchone()

答案 1 :(得分:0)

Note that pymssql.connect does not have an 'authentication' parameter。您将它作为命名的arg传递,它是无效的,以及您看到错误的原因。

请参阅this example,了解如何使用Windows身份验证进行连接:

import re

def address_list(address_range):
    begin,end = address_range.split('-')     
    Nb,Ne=re.findall(r"\d+", address_range)

    #we deduce the paading from the digits of begin
    padding=len(re.findall(r"\d+", begin)[0]) 

    #first we decide whether we should use begin or end as a template for the ouput
    #here we keep the first that is matching something like ab01 or 01ab
    template_base = re.findall(r"[a-zA-Z]+\d+|\d+[a-zA-Z]+", address_range)[0]

    #we make a template by replacing the digits of end by some format syntax
    template=template_base.replace(re.findall(r"\d+", template_base)[0],"{{:0{:}}}".format(padding))

    #print("template : {} , example : {}".format(template,template.format(1)))

    return [template.format(x) for x in range(int(Nb), int(Ne)+1)]  

print(address_list('1-12A'))
print(address_list('B01-B12'))
print(address_list('C01-9'))
相关问题