Andrew
Andrew

Reputation: 203

python connecting to Azure database

I am connecting Azure database from python. while doing I have to pass below parameters. What I have to specify in the 'driver' as string.

enter code here

server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT]. 
[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

Upvotes: 1

Views: 974

Answers (1)

Tony Ju
Tony Ju

Reputation: 15629

If you installed Microsoft ODBC Driver 17 on your environment. Then the value for driver should be driver = '{ODBC Driver 17 for SQL Server}'. You can download different ODBC drivers here.

The working python samle:

    import pyodbc
    server = 'test.database.windows.net'
    database = ''
    username = ''
    password = ''
    driver = '{ODBC Driver 17 for SQL Server}'
    cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server +
                      ';PORT=1433;DATABASE='+database+';Uid=testsql;Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30')
    cursor = cnxn.cursor()
    cursor.execute(
        "select * from Persons")
    row = cursor.fetchone()
    while row:
        print(str(row[0]) + " " + str(row[1]))
        row = cursor.fetchone()

Upvotes: 1

Related Questions