Python 带有sqlite3数据库存储问题的简单CLI todo管理器

Python 带有sqlite3数据库存储问题的简单CLI todo管理器,python,sqlite,command-line,argparse,Python,Sqlite,Command Line,Argparse,我目前正在尝试制作一个命令行todo管理器,允许用户输入任务,删除它并列出任务。从我尝试的可视化来看,它并没有像我想象的那样,这是我第一次使用sqlite3 我正在努力实现的目标: 将任务存储在数据库中,该数据库将自动向其添加递增ID。 例如: python todo.py -add do the laundry on Sunday [in the database] Id Task 1 do the laundry on Sunday 我的密码 import sqlite3 im

我目前正在尝试制作一个命令行todo管理器,允许用户输入任务,删除它并列出任务。从我尝试的可视化来看,它并没有像我想象的那样,这是我第一次使用sqlite3

我正在努力实现的目标:

将任务存储在数据库中,该数据库将自动向其添加递增ID。 例如:

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主键

cursor.execute('''CREATE TABLE if not exists todo_list(
                      Id INTEGER PRIMARY KEY
                      description TEXT);''')
当我向数据库添加数据时,Id会增加吗

sqlite3.InterfaceError:绑定参数1时出错-可能是不支持的类型

来自argparse的输入是以str的形式输入的,但是您在数据库中将列ID定义为整数。修正是:

cursor.executeINSERT进入todo_列表值?,?,intnum,task, 将任务存储在数据库中,该数据库将自动向其添加递增ID

根据sqlite文档,定义整数PRIMARYKEY将自动递增。只需将一个空值传递给它,sqlite就会为您处理其余部分

在显示和添加任务时,代码中存在一些问题。首先,初始化数据库:

cursor.execute 创建表(如果不存在待办事项列表) id整数主键, 描述文本; 在你的后期编辑之前你是如何拥有它的。然后,将添加到待办事项列表:

请注意,从函数输入中删除num,并为列ID传递None。在get_todo_列表中,您可以更轻松地获取它,如下所示:

def get_todo_列表: cursor=数据库\连接.cursor cursor.executeselect*自待办事项列表 返回cursor.fetchall 解析args的方式也需要修复;对于commands.list,您需要执行以下操作:

elif commands.list is not None:
    print(get_todo_list())
这是因为当您执行app.py-list时,commands.list将是一个[],Python对其求值为False空列表为False。您还应该将函数的内容打印到终端,所以不要忘记这一点。通过以上编辑,我可以在终端上执行以下操作:

python test.py -add Random Task!
python test.py -add Hello World!

python test.py -list

尝试将cursor.executeINSERT插入todo_列表值?、?、intnum、task、,。argparse的输入是以STR的形式输入的,但您在db中将列ID定义为整数。@FelipeFaria是的,这是一个很好的观点!我试图去掉num变量,因为我意识到对于任务中的每个空格,for循环都是一个单独的东西。我会在帖子里编辑我的代码。然而,数据库似乎没有改变,因为我试图获取其中的数据。我会在你编辑文章时回复并编辑它,这样我们就不会在这里来回。当你更新帖子的时候,给我一个更新评论我对此表示歉意,我编辑了一点我的帖子,你的打字错误是正确的。我的数据库似乎不接受任何值,但当我尝试通过命令行输入并列出它时,它确实工作了!这是commands.list的一个有趣的观点。但是我有一个问题,在使用fetchall函数时,它是否总是作为字典返回给用户?嗯,它返回一个元组列表,其中包含表的内容,而不是dict。您可以使用for循环非常轻松地解析这些结果。从printget_todo_列表中删除打印,改为在遍历.fetchall结果的循环中从get_todo_列表函数中打印。此外,还应该提到:您之所以将['Random'、'Task!']视为与简单的Random Task相反的原因!在数据库中是因为argparse。如果在add_to_todo_list函数task=.jointask的第一行中添加,您将看到它将变成随机任务!下次在数据库中执行-add.Yes时,argparse将输入作为列表。这实际上可以让你用它做一些古怪的事情,比如。我很高兴听到你觉得这很有帮助!祝你在学习上好运
python test.py -add Random Task!
python test.py -add Hello World!

python test.py -list
[(1, "['Random', 'Task!']"), (2, "['Hello', 'World!']")]