How to execute raw SQL in Flask-SQLAlchemy app
In this article, we are going to see how to execute raw SQL in Flask-SQLAlchemy using Python.
Install the Flask and Flask-SQLAlchemy libraries using pip
pip install Flask pip install flask_sqlalchemy
To run raw SQL queries, we first create a flask-SQLAlchemy engine object using which we can connect to the database and execute the SQL queries. The syntax is –
Executes a SQL expression construct or string statement within the current transaction.
- statement: SQL expression
In this example, we created a simple flask app that does not have any route but instead runs raw SQL queries. We have created the SQLAlchemy connection and then executed 3 different raw SQL queries. The first query creates the user’s table. The second query inserts some sample records in the table. The third query fetches all the records and displays them in the terminal.
In all three cases, we have used the db.engine.execute() method. The db.engine provides an SQLAlchemy engine connection and the execute method takes in a SQL query to execute the request.
In this example, we have created 2 different routes to work with. These routes will act as an API where we can send a POST request with a query key in the body. The value for this query key will be the raw SQL query that we need to execute. The get_results API will be used to fetch the records that we get from the SELECT query. The execute_query API is used to execute raw SQL queries and will return the response message if the query is successfully executed or not.
We will test the routes through POSTMAN. Following are the 3 cases that are tested using POSTMAN.
1. Running a SELECT query to fetch all the records through the get_results API
2. Next, we will test the execute_query API for a valid INSERT query
3. Lastly, we will put any random query and see if we get any error message