I need to write a script with python sqlalchemy that searchs if a database exist, if the database exists it should query the database else create database and tables.
Pseudocode:
if db exists cursor.execute(sql) else create db test; create tables; insert data;
It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query.
Since SQLAlchemy relies on the DBAPI specification to interact with databases, the most common database management systems available are supported. PostgreSQL, MySQL, Oracle, Microsoft SQL Server, and SQLite are all examples of engines that we can use alongside with SQLAlchemy.
In SQLAlchemy documentation it is written. MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.
Return the first result of this Query or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).
You can use the sqlalchemy.engine.base.Engine.connect()
method, which will raise a OperationalError
if the database does not exist.
import sqlalchemy as sqla from sqlalchemy import create_engine from sqlalchemy.exc import OperationalError db = sqla.create_engine(database_uri) try: db.connect() db.execute(sql) except OperationalError: # Switch database component of the uri default_database_uri = os.path.join(os.path.dirname( str(db.engine.url)), 'mysql') db = sqla.create_engine(default_database_uri) # Create your missing database/tables/data here # ...
An alternate way if you don't mind to import other libs is to use sqlalchemy_utils. Then database_exists
does what you expect, which you may pass the sqlalchemy database uri.
if database_exists('sqllite:////tmp/test.db'): do_stuff_with_db(db)
http://sqlalchemy-utils.readthedocs.org/en/latest/database_helpers.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With