Simple Python script that runs SQL scripts against a given SQLite database

Many of the search hits for my blog are along the lines of “python sqlite script”. I really hope those folks find what they are looking for.

I thought I might add this really simple script to run SQL script files against a SQLite database. I use this script all the time. Especially when I only want to make a tiny change to my database to test something, I find find it faster and more convenient to quickly type the SQL into a text file and run a python script from the command line, than it would have been through some SQLite interaction GUI. It becomes especially convenient if I use it alongside LINQPad – I can make changes using the command line, and run queries via LINQPad.

The script is really simple and requires no explanation, just some warnings. It targets Python 2.7 and won’t work in Python 3 as is. The exception handling does nothing except tell you “something” went wrong.

It doesn’t do queries – it only runs scripts against the database but reads no values back. But you can use it for create, insert, update and delete.

The script should be ready to use as is, and the command line is as follows:

python.exe .\ script.sql database.sqlite

If the database file does not exist, it will be created, so you can use this script to create a new SQLite database.

Below is the code, hosted in a gist – if you improve on this by adding better exception handling or whatever, please submit the changes, so we can all benefit Smile

Hope this helps!

This entry was posted in Software Development and tagged , , , , . Bookmark the permalink.

2 Responses to Simple Python script that runs SQL scripts against a given SQLite database

  1. Sorry for my ignorance, but can you integrate this script with django? For example, it’s possible to run the script just when a button inside a template is clicked?

  2. pietermuller says:

    Hi Hugo, I’m sorry, I haven’t worked with django before.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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