1

Im new in using sql alchemy and i am starting with creating connection. I encounter challenge in creating the connection string and I am not sure if the format of the connection string is correct. Specifically my error is the server cannot be found, but when I try it using pyodbc, the credentials are correct(credentials here are dummy only for posting purposes).

I also wanna know what can be the code to prompt if my connection is success or not. I am connecting to MS SQL SERVER.

import urllib import sqlalchemy as sal import pyodbc # DEFINE THE DATABASE CREDENTIALS user = 'user' password = 'pass' host = 'hostname' port = 'port' database = 'TEST_DB' connection_string = "DRIVER={SQL Server};SERVER=host:port;DATABASE=database;UID=user;PWD=password" connection_string = urllib.parse.quote_plus(connection_string) connection_string = "mssql+pyodbc:///?odbc_connect=%s" % connection_string try: engine = sal.create_engine(connection_string) connection = engine.connect() print("Passed") except: print("failed!") 
1
  • Solve this your question, sof Commented Aug 25, 2023 at 18:55

1 Answer 1

0

You can format the connection string like this:f"mssql+pyodbc://{user}:{password}@{host}:{port}/{database}?driver=SQL+Server"

Don't forget to put a connection.close() at the end and it is also a good idea to print out a traceback when an error occurs.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.