【发布时间】:2019-08-07 15:18:29
【问题描述】:
我尝试编写此代码,希望它会自动递增,但不知何故它不起作用,并且 id 列中的输出条目设置为“无”。我也尝试了其他答案,但它们都不起作用。请帮忙如果可能的话。
代码如下:
import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year int,isbn int)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
def view():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM book ")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert("sample","abc",2003,123456)
insert("sample2","def",2003,123457)
print(view())
这是输出:
[(None, 'sample', 'abc', 2003, 123456), (None, 'sample2', 'def', 2003, 123457)]
【问题讨论】:
-
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY AUTOINCREMENT,title text,author text,year int,isbn int)")。此外,说明您要插入的值也是一个好习惯,所以cur.execute("INSERT INTO book (title, author, year, isbn) VALUES (?,?,?, ?)",(title,author,year,isbn)) -
您发布的表定义和插入语句应该会导致 sqlite 自动将值分配给 id 列。您是否预先使用具有不同表定义的数据库?
IF NOT EXISTS隐藏它很容易做到。也许INT PRIMARY KEY代替? -
问题已解决。我没有使用
IF NOT EXISTS,而是先使用DROP TABLE,然后使用CREATE TABLE再次创建表。感谢您的建议。
标签: python python-3.x sqlite auto-increment