Skip to content

Instantly share code, notes, and snippets.

@aafaque33
Last active December 13, 2018 17:20
Show Gist options
  • Save aafaque33/8fb9b66454e9b6691cc0b797c6cafa08 to your computer and use it in GitHub Desktop.
Save aafaque33/8fb9b66454e9b6691cc0b797c6cafa08 to your computer and use it in GitHub Desktop.
Read UTF-8 queries from sql script and write in sqlite db using python

Usage

python sqlite_read.py -h
usage: sqlite_read.py [-h] --script SCRIPT --db DB

Read sql script into Sqlitedb

optional arguments:
  -h, --help       show this help message and exit
  --script SCRIPT  Add sql script file (along with full path)
  --db DB          Add sqlite db file (along with full path)

python sqlite_read.py --script=sql_script_file_path --db=sqlite_db_file_path

import os
import argparse
import sqlite3 as sqlite
import codecs
def _file_exists(filepath):
if os.path.exists(filepath):
return filepath
else:
raise argparse.ArgumentTypeError('Not a valid file or path')
def execute_sql(script_file, db_file):
try:
conn = sqlite.Connection(db_file)
cur = conn.cursor()
print("Reading the Sql Script...")
with codecs.open(script_file, 'r', 'utf-8') as f:
sql_queries = f.read()
print("Executing script againt db...")
cur.executescript(sql_queries)
conn.commit()
print("Succesfully executed the script...")
except Exception as e:
print("Some issue executing the script...")
print(e)
finally:
conn.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Read sql script into Sqlitedb")
parser.add_argument("--script", required=True, type=_file_exists, help="Add sql script file (along with full path)")
parser.add_argument("--db", required=True, type=_file_exists, help="Add sqlite db file (along with full path)")
args = parser.parse_args()
args_dict = vars(args)
script_file = args_dict['script']
db_file = args_dict['db']
execute_sql(script_file, db_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment