Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Get database name from engine

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.

like image 743
dakes Avatar asked Nov 30 '18 09:11

dakes


People also ask

What does DB Drop_all () do?

You delete everything in the database using the db. drop_all() function to add the tags and post_tag tables safely and to avoid any of the common issues related to adding new tables to a database. Then you create all the tables anew using the db. create_all() function.

What is DB Create_all ()?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student.

What does Create_all do in SQLAlchemy?

Sqlalchemy create_all method is used to create a new table into the database. This method will first check whether the table exists in the database or not if suppose it has found an existing table it will not create any table.


1 Answers

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
like image 189
cybertoast Avatar answered Sep 25 '22 20:09

cybertoast