Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute an SQLite script from within python?

Tags:

python

sqlite

My SQLite script works fine, when I type:

.read 'dummy.sql'

from within the SQLite shell.

However, the following Python code is not doing it properly. I'm getting a syntax error in line 5.

import sqlite3
db = sqlite3.connect('scheduling.db')
cursor=db.cursor()
a='''.read "scheduling.sql"'''
cursor.execute(a)
db.commit
db.close()

I know I'm doing something wrong with the quotes. How do I make this work?

like image 867
vegebond Avatar asked Jan 21 '19 12:01

vegebond


People also ask

How do I read a .SQL file in Python?

Connecting to SQLite Database Then create a connection using connect() method and pass the name of the database you want to access if there is a file with that name, it will open that file. Otherwise, Python will create a file with the given name.

How do I run multiple SQLite statements in Python?

In SQLite using the executescript() method, we can execute multiple SQL statements/queries at once. The basic execute() method allows us to only accept one query at a time, so when you need to execute several queries we need to arrange them like a script and pass that script to the executescript() method.


1 Answers

The workaround I would recommend is to read the contents of the .sql file into a Python string variable, as you would read any other text file, and then call executescript. Unlike execute, executescript can execute many statements in one call. For example, it will work correctly if your .sql contains the following:

CREATE TABLE contacts (
 contact_id INTEGER PRIMARY KEY,
 first_name TEXT NOT NULL,
 last_name TEXT NOT NULL
);

INSERT INTO contacts (contact_id, first_name, last_name)
VALUES (1, 'John', 'Smith');

Here's the full Python snippet that you'll need:

import sqlite3

with open('scheduling.sql', 'r') as sql_file:
    sql_script = sql_file.read()

db = sqlite3.connect('scheduling.db')
cursor = db.cursor()
cursor.executescript(sql_script)
db.commit()
db.close()
like image 123
sjw Avatar answered Sep 30 '22 07:09

sjw