sqlite3无法创建/插入表

时间:2015-12-10 18:13:09

标签: python sqlite

我在做:

    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()

但它一直在输出:

Db Creation Successful
Table Creation NOT Successful
Insert NOT Successful

有人看到我做错了吗?我正在关注这个guide,但我看不到发现这个问题。感谢。

3 个答案:

答案 0 :(得分:1)

你之前有逗号)在这个地方:

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

删除它。

答案 1 :(得分:0)

试试这个:

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')

您的错误是创建表格。 'with'是我添加的一个加号,当块因任何原因完成时它会关闭连接,因此你不需要'finally'块。

如果您有任何疑问,请随时询问。

答案 2 :(得分:0)

盲目地敲打try..except而不显示异常中的错误只会导致你的悲伤和心痛,使用可用的异常列出特定的错误。

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()