0

I've got some problems with my SQLite database. I've got some sql script like this:

CREATE TABLE Workers(
    Id_worker   INT NOT NULL PRIMARY KEY,
    Name        VARCHAR(20) NOT NULL,
    Surname     VARCHAR(30) NOT NULL,
    Id_job      INT NOT NULL, -- REFERENCES Job(Id_job),
    Adress      VARCHAR(30) NOT NULL,
    Start_date  SMALLDATETIME NOT NULL
);

CREATE TABLE OldWorkers(
    Id_arch     INT NOT NULL PRIMARY KEY,
    Name        VARCHAR(20) NOT NULL,
    Surname     VARCHAR(30) NOT NULL,
    Id_job      INT NOT NULL, -- REFERENCES Job(Id_job),
    Adress      VARCHAR(30) NOT NULL,   
    Start_date  SMALLDATETIME NOT NULL,
    Delete_date    SMALLDATETIME NOT NULL
);
CREATE TRIGGER OldWorkersTrigger
AFTER DELETE ON Workers
FOR EACH ROW
BEGIN 
INSERT INTO OldWorkers (Id_arch, Name, Surname, Id_job, Adress, Start_date) VALUES (old.Id_arch, old.Name, old.Surname, old.Id_job, old.Adress, old.Start_date,datatime('now'));
END;

I try to do it in Python 2.7.4 by sqlite3 like this:

conn = sqlite3.connect('Company.db')
c = conn.cursor()
fd = open('MyScript.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
i = 1 
# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    print i," : ",command
    i = i + 1
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

But in command wiht my trigget it returns: Command skipped: near ")": syntax error. And after END; it returns: Command skipped: cannot commit - no transaction is active

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You are splitting the file at every semicolon, but the CREATE TRIGGER statement has an embedded semicolon.

To check whether a statement is complete, try the sqlite3.complete_statement function.

CL.
  • 173,858
  • 17
  • 217
  • 259
  • Ofcourse! I must remember that every problem begins with semicolon :P Now with coplete_statement it works good. Thanks CL :) – user3192222 Jan 14 '14 at 18:42
-2

SQLite can ingest and execute arbitrary SQL statements. Why not consider the following (untested):

conn = sqlite3.connect('Company.db')

c = conn.cursor()

with open('MyScript.sql', 'r') as fd:

try:

    c.execute(fd.read())

except OperationalError, msg:

    print "Command skipped: ", msg
smitty1e
  • 27
  • 3