Connecting to MS SQL Server with Windows Authentication using Python?

后端 未结 3 1874
一整个雨季
一整个雨季 2020-12-01 00:14

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

3条回答
  •  感动是毒
    2020-12-01 00:41

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

提交回复
热议问题