Jshee
Jshee

Reputation: 2686

sqlite3 failing to create/insert table

Im doing:

    try:
        conn = sqlite3.connect('bags_of_coins.db')
        print('Db Creation Successful')
    except:
        print('Db Creation NOT Successful')
    try:
        conn.execute('''CREATE TABLE bags
            (ID INTEGER PRIMARY KEY,
            bag TEXT    NOT NULL,
            );''')

        print('Table Creation Successful')
    except:
        print('Table Creation NOT Successful')
    try:
        conn.execute("INSERT INTO bags (bag) \
            VALUES ('test')");
        conn.commit()
    except:
        print('Insert NOT Successful')

    #finally.
    conn.close()

But it keeps outputting:

Db Creation Successful
Table Creation NOT Successful
Insert NOT Successful

Does anyone see anything i'm doing wrong? I was following this guide but I cant see to spot the issue. Thanks.

Upvotes: 0

Views: 70

Answers (3)

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

Blindly banging out try..except without showing the error from the exception is just going to cause you grief and heartache, use the exception available to list the specific error.

import sqlite3
try:
    conn = sqlite3.connect('bags_of_coins.db')
except sqlite3.Error as e:
    print('Db Creation NOT Successful', str(e))
mycursor = conn.cursor()
try:
    mycursor.execute("CREATE TABLE bags (ID INTEGER PRIMARY KEY,bag TEXT NOT NULL)")
except sqlite3.Error as e:
    print("Table creation failed", str(e))
try:
    mycursor.execute("insert into bags (bag) values (?)", (['test']))
    conn.commit()
except sqlite3.Error as e:
    print("table insert failed", str(e))

#finally.
conn.close()

Upvotes: 0

epinal
epinal

Reputation: 1465

Try this:

import sqlite3

conn = None
try:
    conn = sqlite3.connect('bags_of_coins.db')
    print('Db Creation Successful')
except:
    print('Db Creation NOT Successful')
try:
    with conn:
        conn.execute("CREATE TABLE bags (ID INTEGER PRIMARY KEY, bag TEXT NOT NULL);")
        print('Table Creation Successful')

        cursor = conn.execute("INSERT INTO bags (bag) VALUES ('test')")
        conn.commit()
        print("Insert Successful" if cursor.rowcount > 0 else "Insert NOT Successful")
except:
    print('Table Creation NOT Successful')

Your error was creating the table. The 'with' is a plus I added, it takes care of closing the connection when the block finish by any reason so you don't need the 'finally' block.

Don't hesitate to ask if you have any doubt.

Upvotes: 0

Matt
Matt

Reputation: 1308

You have comma before ) in this place:

CREATE TABLE bags
(ID INTEGER PRIMARY KEY,
bag TEXT    NOT NULL,  <- here
);

delete it.

Upvotes: 1

Related Questions