我目前正在尝试制作一个命令行Todo管理器,该管理器将允许用户输入任务,将其删除并列出该任务。从我想像的过程来看,它并没有达到我的预期,这是我第一次使用sqlite3。
我想要达到的目标:
示例:
python todo.py -add do the laundry on Sunday
[in the database]
Id Task
1 do the laundry on Sunday
我的代码。
import sqlite3
import argparse
def parse_args():
desc = 'Todo manager for storing and removing tasks'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-a", "--add", "-add", help="To add a new item to the list",
type=str, nargs="+")
parser.add_argument("-r", "-remove", "--remove", help="To remove an item from the list",
type=int)
parser.add_argument("-l", "-list", "--list", help="displays the tasks or task in the list",
nargs="*")
args = parser.parse_args()
return args
@staticmethod
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def get_todo_list():
database_connection.row_factory = dict_factory
cursor = database_connection.cursor()
cursor.execute("select rowid, * FROM todo_list")
return cursor.fetchall()
def add_to_todo_list(num,task):
cursor = database_connection.cursor()
cursor.execute("INSERT INTO todo_list VALUES (?)", (str(task),))
database_connection.commit()
def remove_from_todo_list(rowid):
cursor = database_connection.cursor()
cursor.execute("DELETE FROM todo_list WHERE rowid = ?", (rowid,))
database_connection.commit()
if __name__ == '__main__':
commands = parse_args()
# Creating table for database using sqlite
database_connection = sqlite3.connect('todo_list.db')
cursor = database_connection.cursor()
cursor.execute('''CREATE TABLE if not exists todo_list(
description TEXT);''')
database_connection.commit()
if commands.add:
# Stops accepting tasks when there is a blank task as input.
if not commands.add == ' ':
add_to_todo_list(commands.add)
elif commands.remove:
remove_from_todo_list(commands.remove)
elif commands.list:
get_todo_list()
但是,当我尝试存储数据时,我的数据库不接受任何值。通过在创建表格时将ID设置为Id INTEGER PRIMARY KEY
,即
cursor.execute('''CREATE TABLE if not exists todo_list(
Id INTEGER PRIMARY KEY
description TEXT);''')
当我向数据库添加数据时,Id会增加吗?
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.