How to execute SQL code in Python

 

You can make this easier on yourself by using a convenient function executescript() in Python’s sqlite3 package:

import sqlite3

connection = sqlite3.connect(‘DataBaseName.db’)

def scriptexecution(filename):

with open(filename, ‘r’) as s:

sql_script = s.read()

connection.executescript(sql_script)

s.closed

scriptexecution(‘sql_file_1.sql’)

scriptexecution(‘sql_file_2.sql’)

Review the documentation: sqlite3 – DB-API 2.0 interface for SQLite databases – Python 2.7.13 documentation

Be careful if your SQL files are very large, because reading the whole file at once into the sql_script might consume a lot of memory.

 

Author: Aditya Bhuyan

I am an IT Professional with close to two decades of experience. I mostly work in open source application development and cloud technologies. I have expertise in Java, Spring and Cloud Foundry.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s