Zakiullah Khan
Zakiullah Khan

Reputation: 1475

How to execute user defined SQL query at run time using SQLAlchemy?

I have a use case implementation for which I am trying to identify the solution, the implementation is as follows :

If you notice above all the parameters for SQLAlchemy to work are user defined at run time, I am trying to implement the function in python which consumes the above connection parameters and sql query, executes the query on successful connection and returns the query result. Any point of direction or help on this would be great.

Thanks

Upvotes: 0

Views: 570

Answers (1)

Bogdan
Bogdan

Reputation: 8246

I'm having something like this as part of a larger project, so far only for sqlite and postgres but this can be generalized.

For start if you expect the user to know DATABASE_TYPE ( like MySQL, pgsql, sqlite or any db supported by SQLAlchemy), HOST, PORT, SCHEMA_NAME, USER_NAME and PASSWORD you could just ask for the DB URL to make your life a little easier.

After that you can test the connection by:

    from sqlalchemy import create_engine
    try:
        engine = create_engine(url)           
        connection = engine.connect()
        connection.close()
    except Exception, e:
        LOGGER.exception(e)
        raise MyCusomException('Could not initialize db. Invalid URL.') 

Cusom sql queries can be executed using the text() construct as shown here.

Upvotes: 1

Related Questions