SQL Server Use my Microsoft account to connect to an Azure SQL Database (with Azure Active Directory)

csga3l58  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(103)

I am using Visual Studio Code to connect to a SQL Server. I'm trying to establish a connection between them using my Microsoft account. I need this connection to execute with Python. How can I do that? With the code I currently have I am getting a connection failed.

Here is my code:

# Add libraries needed for connecting to Azure SQL Database
import sqlalchemy
from sqlalchemy import exc
import urllib
import time

#~ Connection Parameters for SQL Server
server   = 'Server_name.database.windows.net'
database = 'database_name'
username = 'username'
password = 'password'   
# driver   = '{ODBC Driver 17 for SQL Server}'
driver   = 'SQL Server' # Try this one if top doesn't work
# print (pyodbc.drivers()) # Used to see what drivers you have

#~ Setup connection strings for API
connection_string_1 = f"""Driver={driver};Server=tcp:{server},1433;Database={database}; Uid={username};Pwd={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"""
connection_string_2 = urllib.parse.quote_plus(connection_string_1)
connection_string_3 = 'mssql+pyodbc:///?autocommit=true&odbc_connect={}'.format(connection_string_2)

#~ Try to connect to the DB. Print error and close if unsuccessful.
try:
    engine = sqlalchemy.create_engine(connection_string_3, echo=False) #Echo will display all queries ran in the command prompt. Useful for debugging.
    DB_connection = engine.connect()
except exc.SQLAlchemyError:
    print('LDAP Connection failed: check password.')
    print('Program aborting and closing in 5 seconds.')
    time.sleep(5)
    quit()

print('File Complete - Connection')
2eafrhcq

2eafrhcq1#

Try to use the following code for connection.

import pyodbc
import sqlalchemy

server = "your_server_name.database.windows.net"
database = "your_database_name"
username = "your_username"
password = "your_password"
driver = "{ODBC Driver 17 for SQL Server}"
connection_string = f"Driver={driver};Server={server};Database={database};Uid={username};Pwd={password};Authentication=ActiveDirectoryPassword"
try:
    conn = pyodbc.connect(connection_string)
    cursor = conn.cursor()
    print("Connected to SQL Server")

    # Now, you can use 'cursor' to execute SQL queries.
except pyodbc.Error as e:
    print(f"Connection failed: {e}")

Note: You need to install pyodbc and sqlalchemy packages.

pip install pyodbc sqlalchemy

相关问题