jeudi 3 septembre 2015

How to create a db file in sqlite3 using a schema file from within python

I have a schema file myschema.sql and a database file mydatabase.db using sqlite3 within python (specifically python 2.7) I would like to generate this schema in to my database.

I am aware that via the command line one can do the following

sqlite3 mydatabase.db < myschema.sql

and alternatively I can do the following but this may not work on all systems:

import os
os.popen("sqlite3 mydatabase.db < myschema.sql")

Which is not what I am after, since it may not work on some platforms.

I would also like to avoid something like:

import sqlite3
schema_str = open("myschema.sql","r").read()
connection = sqlite3.connect("mydatabase.db")
cur = connection.cursor()
list_of_insertions = map(lambda x: x.lstrip().replace("\n"," "),
                         schema.split(";"))
map(cur.execute, list_of_insertions)
connection.commit()

So parsing the file and creating the tables seperately is not what I would like either I am just looking for a python-sqlite equivalent of what can be done with the commandline tool.

Aucun commentaire:

Enregistrer un commentaire