简体   繁体   English

Python SQLite ToDo脚本

[英]Python SQLite ToDo script

I'm trying to make a script that asks the user to input a task, the task is then stored in a SQLite database. 我正在尝试制作一个脚本,要求用户输入任务,然后将该任务存储在SQLite数据库中。 I am having a problem getting my delete function to work. 我在使删除功能正常工作时遇到问题。 Also when I input a new task I have to encapsulate in quotes in order to make it run. 同样,当我输入一个新任务时,我必须用引号将其封装起来以使其运行。

import sqlite3
import sys 

con = sqlite3.connect('taskmgr.db')

def create_db():
    with con:
        c.execute("DROP TABLE IF EXISTS ToDo")
        c.execute("CREATE TABLE ToDo(Id int, Task char20, Due char20)") 

def select_task():
    with con:
        cursor = con.execute("SELECT Id, Task, Due from ToDo")
        for row in cursor:
            print "Id:" ,row[0]
            print "Task:" ,row[1]
            print "Due:" ,row[2]

def insert_task():
    with con:
        print("New Task\n")
        Id = input("Enter Id: ")
        Task = input("Enter Task: ")
        Due = input("Enter Due Date: ")
        c.execute("INSERT INTO ToDo VALUES(?, ?, ?)", (Id, Task, Due))
        con.commit()

def delete_record():
    with con:
        print("Enter task Id to delete:")
        user = int(input())
        c.execute("DELETE FROM ToDo WHERE Id=?",(user))

c = con.cursor()        
create_db()

target= int(8)
while target != 9:
    target=int(input("\nGood Morning Curtis!\n \nSelect option:\n 1.New Task\n 2.Select Task\n 3.Delete Task\n 9.Quit\n\nUser: "))

    if target ==1:
        insert_task()

    elif target ==2:
        select_task()

    elif target ==3:
        delete_record()

    elif target ==9:
        print("good bye")

Regarding the input requiring quotes, for Python 2 use raw_input() instead of input() . 关于需要引号的输入,对于Python 2,请使用raw_input()而不是input()

The other problem is with the execute statement, specifically the values for the parameterised query needs to be of type tuple (or list), however, you are passing in an integer value. 另一个问题是execute语句,特别是参数化查询的值必须是元组(或列表)类型,但是,您传入的是整数值。 Try changing it to this: 尝试将其更改为此:

c.execute("DELETE FROM ToDo WHERE Id=?",(user,))

The reason is that wrapping a single value in parentheses does not create a tuple: 原因是将单个值括在括号中不会创建元组:

>>> for user in 1, (1), (1,):
...     print user, type(user)
... 
1 <type 'int'>
1 <type 'int'>
(1,) <type 'tuple'>

From the above you can see that (1) is still 1 and is of type int. 从上面可以看到(1)仍然是1并且是int类型的。 Wrapping it in () did not convert it to a tuple. 将其包装在()中不会将其转换为元组。 However, (1,) is a tuple. 但是, (1,)是一个元组。 Alternatively you could pass a list of the parameters, eg 或者,您可以传递参数列表,例如

c.execute("DELETE FROM ToDo WHERE Id=?",[user])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM