缩短SQLite功能

时间:2018-06-02 19:40:32

标签: python-3.x sqlite

我是python的新手,我想知道是否可以缩短一些重复代码,如下面的函数。我正在制作一个程序,它使用sqlite3来记录用户的个人(正在运行)记录和有关它们的信息。程序然后可以显示它们,订购它们等。下面的代码用于我的删除功能。谢谢你的帮助!

def delete_pr(conn, c, command):
if (len(command) == 1):
    print("Delete what???")
if (len(command) == 2): 
    c.execute("DELETE FROM personal_records WHERE (event = ?)", (command[1], ))
    conn.commit()
if (len(command) == 3):
    c.execute("DELETE FROM personal_records WHERE (event = ?) AND (time = ?)", (command[1], command[2]))
    conn.commit()
if(len(command) == 4):
    c.execute("DELETE FROM personal_records WHERE (event = ?) AND (time = ?) AND (date = ?)", (command[1], command[2], command[3], ))
    conn.commit()
if(len(command) == 5):
    c.execute("DELETE FROM personal_records WHERE (event = ?) AND (time = ?) AND (date = ?) AND (info = ?)", (command[1], command[2], command[3], command[4], ))
    conn.commit()

1 个答案:

答案 0 :(得分:0)

不确定;您可以改进cmd的构建方式(我将其作为练习留下)。

def delete_pr(conn, c, command):
    if (len(command) == 1):
        print("Delete what???")
    elif len(command)<=5:
        # Build the query out of enough parts to match the length of command
        cmd = "".join(["DELETE FROM personal_records WHERE (event = ?)"," AND (time = ?)"," AND (date = ?)"," AND (info = ?)"][:len(command)])
        # Execute it using all but the first element of command
        c.execute( cmd, tuple(command[1:]) )
        conn.commit()