I have a file containing sql commands and I want to execute the commands given in the file and if any command throws any error then ignore the error and execute the next command. Here is a sample file:
x
drop table department;
drop table classroom;
create table classroom
(building varchar(15),
room_number varchar(7),
capacity numeric(4,0),
primary key (building, room_number)
);
create table department
(dept_name varchar(20),
building varchar(15),
budget numeric(12,2) check (budget > 0),
primary key (dept_name)
);
For eg. if the classroom table doesn’t exists then the drop table command will produce an error and the program will terminate. I want that the program keep running and execute all commands in the file.
The problem I’m facing is that the create table
command is in multiple lines so I don’t know how to execute that.
Advertisement
Answer
Take a look at the sqlite3 manual:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
with open('PATH_TO_SQL_FILE', 'r') as fp:
text = fp.read().split(';')
for command in text:
try:
cur.execute(command)
except sqlite3.Error:
pass