我就是找不到我的错误。当我尝试向数据库添加元素时,出现以下错误: 操作错误:表习惯有 7 列,但提供了 8 个值
import sqlite3 #import sqlite
from typing import List
import datetime
from habit import Habit
conn = sqlite3.connect('habits.db') #connect database and set database name to habits.db
c = conn.cursor() #create cursor
#c.execute('DROP TABLE habits')
#create function to execute table
def create_table(): #create new table if todos doesn't exist yet
c.execute("""CREATE TABLE IF NOT EXISTS habits (
position integer
habit_name text,
category text,
duration text,
date_created datetime,
last_date_checked datetime,
streak integer,
status integer
)""") #input all stored fields of model class
create_table()
#create function to insert Habit
def insert_habit(habit:Habit):
c.execute('SELECT count(*) FROM habits') #execute select count(*)
count = c.fetchone()[0] #fetch first item (number of items in table)
habit.position = count if count else 0 #if we have no items we start at 0 otherwise at count
with conn: #open connection; as soon as we get out of conn (context manager) everything will be committed
c.execute('INSERT INTO habits VALUES (:position, :habit_name, :category, :duration, :date_created, :last_date_checked, :streak, :status)', #insert all fields; uses parameter substitutes
{'position': habit.position, 'habit_name': habit.habit_name, 'category': habit.category, 'duration': habit.duration, 'date_created': habit.date_created,
'last_date_checked': habit.last_date_checked, 'streak': habit.streak, 'status': habit.status}) #add dictionary and specify each value
目前的问题出现在函数insert_habit中
您忘记了位置整数后面的逗号,因此您的表格只有 7 列。您可以通过以下方式显示:
import sqlite3
connection = sqlite3.connect('habits.db')
cursor = connection.execute('select * from habits')
names = list(map(lambda x: x[0], cursor.description))
connection.close()
print(names)