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')
1条答案
按热度按时间2eafrhcq1#
Try to use the following code for connection.
Note: You need to install
pyodbc
andsqlalchemy
packages.