首页 > 解决方案 > Python SQLite 删除,其中值为“无”

问题描述

我需要删除值可能为无的数据库条目。我从 ListBox 中获取我的值。该函数如下所示:

    def OnDelete(self, e): 
    num = self.list.GetItemCount()
    for i in range(num):
        if self.list.IsChecked(i):
            itemValueList = []
            for i2 in range(6):
                item = self.list.GetItem(i, i2)

                if item.GetText() == "None":
                    itemValueList.append("")
                else:
                    itemValueList.append(item.GetText()) 

    DBManager.DeleteEntry(itemValueList)

我的 DBManager 中的函数如下所示:

def DeleteEntry(itemValueList):
    # Open Database
    conn = sqlite3.connect('Database.db')
    c = conn.cursor()
    # Delete a row of data
    c.execute('delete from Database where Value1=? and Value2=? and Value3=? and Value4=? and Value5=? and Value6=?',  
              (itemValueList[0], itemValueList[1], itemValueList[2], itemValueList[3], itemValueList[4], itemValueList[5]))

    # Save (commit) the changes
    conn.commit()

因此,在我的情况下,目前 SQLite DB 中的 Value5 和 Value6 是“无”或 NULL。因此,我将添加到 itemValueList 的字符串设置为“”。但这不起作用。数据库条目不会被删除。

我还需要更改哪些列可能没有价值的条目被删除?

谢谢你。

[编辑]:

c.execute('delete from Database where isnull(Value1,"")=? and isnull(Value2,"")=? and isnull(Value3,"")=? and isnull(Value4,"")=? and isnull(Value5,"")=? and isnull(Value6,"")=?',  
          (itemValueList[0], itemValueList[1], itemValueList[2], itemValueList[3], itemValueList[4], itemValueList[5]))

标签: pythonsqlite

解决方案


请参阅SQLite 中的 null 安全相等运算符 <=> 的等价物是什么?. 您应该使用IS运算符而不是=在查询中,它会正确匹配一个NULL值。

然后,您需要更改代码以使用 PythonNone而不是空字符串。这将NULL在准备好的语句中转换为 SQL。

            if item.GetText() == "None":
                itemValueList.append(None)
            else:
                itemValueList.append(item.GetText())

推荐阅读