tomak
tomak

Reputation: 1419

Syntax error when creating database SQLite python

This is my code:

conn.execute("""
        CREATE TABLE IF NOT EXISTS Blockchain_transactions(
        hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
        id INTEGER DEFAULT NULL,
        transaction CHAR DEFAULT NULL
    );""")

It generates a syntax error

sqlite3.OperationalError: near "transaction": syntax error

REMARK: This comes earlier in my code and does not generate the same error

conn.execute("""
        CREATE TABLE IF NOT EXISTS Blockchain_blocks (
        hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
        proof_of_work INTEGER DEFAULT NULL,
        difficulty INTEGER DEFAULT NULL
    );""")

Upvotes: 0

Views: 611

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

transaction is a sqlite keyword.

Change the column name to something different and it will work.

Avoid reserved keywords for column names, or escape them like this:

conn.execute("""
    CREATE TABLE IF NOT EXISTS Blockchain_transactions(
    hash_of_previous_block CHAR PRIMARY KEY DEFAULT NULL,
    id INTEGER DEFAULT NULL,
    `transaction` CHAR DEFAULT NULL
);""")

Other possibilities to escape / quote keywords can be found in the linked keywords page.

Upvotes: 4

Related Questions