Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search for the existence of a database with sqlalchemy

Tags:

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; 
like image 438
Herb21 Avatar asked Feb 25 '13 07:02

Herb21


People also ask

What does SQLAlchemy query return?

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.

What database does SQLAlchemy use?

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.

What is SQLAlchemy MetaData?

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.

What does First () do in SQLAlchemy?

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).


2 Answers

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     # ... 
like image 119
Damien Avatar answered Sep 18 '22 10:09

Damien


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

like image 40
Adrian Saldanha Avatar answered Sep 19 '22 10:09

Adrian Saldanha