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

r1zk6ea1  于 11个月前  发布在  SQLite
关注(0)|答案(2)|浏览(142)

你好,祝你一天好,无论你现在在哪里。我有一个关于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。所以,it throw this error检索数据时出错:no such column:the_text_gotten from the wxpython泰特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()})


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

kulphzqa

kulphzqa1#

如前所述,稍微改变一下概念可能会有所帮助。你可以尝试创建更具体的函数,比如:

def get_subject_by_name(self, subject_name: str):
    query = "SELECT col1 as col_alias1, col2 as col_alias2 FROM subject_table where subject_name = ?"
    cursor.execute(query, (subject_name, ))
    ...

字符串
然后再进行以下操作:

SchoolManagmentSystem.get_subject_by_name(name_to_find)


不建议将用户提供的输入直接插入到查询中,因为可能会受到SQL注入攻击:https://www.w3schools.com/sql/sql_injection.asp
你也可以考虑使用SqlAlchemy和它的ORM,这取决于用例:https://docs.sqlalchemy.org/en/20/index.html

iyzzxitl

iyzzxitl2#

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

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", "where subject_name = ?", (self.subject_name_text.GetValue(),))

相关问题