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 .\RunSQLiteScript.py 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
Hope this helps!