Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute SQL from file in SQLAlchemy

How can I execute whole sql file into database using SQLAlchemy? There can be many different sql queries in the file including begin and commit/rollback.

like image 991
Szymon Lipiński Avatar asked Feb 15 '10 18:02

Szymon Lipiński


People also ask

How do you call a stored procedure using SQLAlchemy?

The easiest way to call a stored procedure in MySQL using SQLAlchemy is by using callproc method of Engine. raw_connection() . call_proc will require the procedure name and parameters required for the stored procedure being called.


2 Answers

sqlalchemy.text or sqlalchemy.sql.text

  • The text construct provides a straightforward method to directly execute .sql files.
from sqlalchemy import create_engine from sqlalchemy import text # or from sqlalchemy.sql import text  engine = create_engine('mysql://{USR}:{PWD}@localhost:3306/db', echo=True)  with engine.connect() as con:     with open("src/models/query.sql") as file:         query = text(file.read())         con.execute(query) 
  • SQLAlchemy: Using Textual SQL
    • text()
like image 182
Erfan Avatar answered Oct 10 '22 03:10

Erfan


I was able to run .sql schema files using pure SQLAlchemy and some string manipulations. It surely isn't an elegant approach, but it works.

# Open the .sql file sql_file = open('file.sql','r')  # Create an empty command string sql_command = ''  # Iterate over all lines in the sql file for line in sql_file:     # Ignore commented lines     if not line.startswith('--') and line.strip('\n'):         # Append line to the command string         sql_command += line.strip('\n')          # If the command string ends with ';', it is a full statement         if sql_command.endswith(';'):             # Try to execute statement and commit it             try:                 session.execute(text(sql_command))                 session.commit()              # Assert in case of error             except:                 print('Ops')              # Finally, clear command string             finally:                 sql_command = '' 

It iterates over all lines in a .sql file ignoring commented lines. Then it concatenates lines that form a full statement and tries to execute the statement. You just need a file handler and a session object.

like image 33
Joao Felipe Santos Avatar answered Oct 10 '22 04:10

Joao Felipe Santos