14

After creating an SQLALchemy engine like this

engine = create_engine('mssql+pyodbc://user:pass@dbserver:port/db_name?driver=ODBC+Driver+13+for+SQL+Server)

Is there a way to get db_name from the engine-object? I know I can parse the name from the connection string but is there a better way of doing this? I had a look at the SQLAlchemy-API but couldn't find an answer.

1

1 Answer 1

38

The engine provides the connection information, so you can access those parameters. For example, if you're in the debugger, you can do:

(pdb) pp dir(dbconn.engine.url)
[...
 'database',
 'drivername',
 'get_backend_name',
 'get_dialect',
 'get_driver_name',
 'host',
 'password',
 'password_original',
 'port',
 'query',
 'translate_connect_args',
 'username']

So the simple way to get at the database name is:

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

1 Comment

For anyone else looking through wondering how they get it from a sqlalchemy session object: session.bind is the engine. So it's session.bind.url.database

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.