Creek Barbara
Creek Barbara

Reputation: 647

Python/Sqlite3 : Exception has occurred: sqlite3.OperationalError

I'm trying to create a function that will handle API error messages but I get this error message in Python:

Exception has occurred: sqlite3.OperationalError
near "Test4": syntax error

The server response is:

{"message":"Failed to validate one or more request parameters","validationErrors":["Budget name must be unique. 'Test4 - X4574747-PHONE' already exits"]}

And my code is:

def error():
    if "message" in r.json():
        logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " : " + r.json()['message']
        c.execute("INSERT INTO log VALUES ('"+ logText +"')")
        conn.commit()
        if "validationErrors" in r.json():
            logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " : " + r.json()['validationErrors'][0]
            c.execute("INSERT INTO log VALUES ('"+ logText +"')")
            conn.commit()
        os._exit(1)

I can't put my finger on what causes this error. Any help would be appreciated. Thank you.

Upvotes: 0

Views: 1104

Answers (1)

sashaaero
sashaaero

Reputation: 2908

logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " : " + r.json()['validationErrors'][0]
c.execute("INSERT INTO log VALUES ('"+ logText +"')")

You are sending this SQL INSERT INTO log VALUES ('2018-12-10 23:31:26 : Budget name must be unique. 'Test4 - X4574747-PHONE' already exits') and as you see you close ' quote before Test4 and that's why SQL doesn't understand what's going on after closing quote.

Use c.execute("INSERT INTO log VALUES (?)", [logText])

Dan's code works, but I don't understand it.

? means pass argument from given arguments list. Which is [logText]. It is better to use this way to avoid SQL injections.

See here

Upvotes: 1

Related Questions