可重用Python函数从sqlite表检索数据的问题

问题描述 投票:0回答:1

无论你们现在身在何处,大家好,美好的一天。我有一个关于 python 可重用函数从 sqlite 数据库检索数据的问题。我所说的可重用是指我可以插入任何需要它的代码片段的函数。如果你有正确的名字,请毫不犹豫地教育我,我愿意向你学习。 无论如何,下面是代码。

def retrieve_data(self, table_name, columns="*", condition=""):
    try:
        # Construct the SELECT query
        select_query = f"SELECT {columns} FROM {table_name} {condition};"

        # Execute the select query
        cursor.execute(select_query)

        # Fetch all rows
        result = cursor.fetchall()

        return result

    except sqlite3.Error as e:
        print(f"Error retrieving data: {e}")
        return None

现在的问题是,最初当我在代码中调用上述函数时,它将从 wxpython 文本小部件获取的值作为列而不是该列中的值,从而引发列不存在错误。例如,列名称是column_name,用户从文本小部件输入的值是value_in_column,它将value_in_column作为column_name。因此,它会抛出此错误 Error retriving data: no such column: the_text_gotten from the wxpython tet Entry widget.

检查下面我用来调用可重用函数的代码。

def add_subject(self, event):
    if self.subject_name_text.GetValue()!="":
        get_subject_list = SchoolManagementSystem.retrieve_data(SchoolManagementSystem, "subject", "subject_name", f"where subject_name = {self.subject_name_text.GetValue()}")

        subject_list = list(get_subject_list)
        if self.subject_name_text.GetValue() in subject_list:
            print(f"Class {self.subject_name_text.GetValue()} already exists.")
        else:
            subject_list.append(self.subject_name_text.GetValue())
            print(f"Subject {self.subject_name_text.GetValue()}")
            print(subject_list)
        SchoolManagementSystem.insert_row(SchoolManagementSystem, "subject", {"subject_name":self.subject_name_text.GetValue()})

我尝试修改条件参数中的字符串,因为我怀疑这就是我头痛的根源,但我没有成功。因此,我把它带到这里,请专家帮助我。我期待您的有用回复。谢谢。

python function sqlite
1个回答
0
投票

您需要将输入的值放在引号中。

f"where subject_name = '{self.subject_name_text.GetValue()}'"

但是,像这样直接将值替换到查询字符串中并不是一个好主意(例如,如果值包含引号,则它将不起作用),您应该使用带有占位符和单独参数列表的查询。

def retrieve_data(self, table_name, columns="*", condition="", values=()):
    try:
        # Construct the SELECT query
        select_query = f"SELECT {columns} FROM {table_name} {condition};"

        # Execute the select query
        cursor.execute(select_query, values)

        # Fetch all rows
        result = cursor.fetchall()

        return result

    except sqlite3.Error as e:
        print(f"Error retrieving data: {e}")
        return None

然后你这样称呼它:

get_subject_list = SchoolManagementSystem.retrieve_data(SchoolManagementSystem, "subject", "subject_name", f"where subject_name = ?", (self.subject_name_text.GetValue(),))
© www.soinside.com 2019 - 2024. All rights reserved.