繁体   English   中英

为什么这个 SQL 查询失败?

[英]Why does this SQL query fail?

我有一个数据库 class 抽象了一些基本的 crud 逻辑。

问题在于 fetch_single 方法:

sql_insecure 查询工作正常,并返回预期结果。

sql_prepared 查询不返回任何错误,但也不返回任何与参数匹配的结果,当它们明显存在于数据库中时。

sql_prepared 遵循与 insert_single 方法实现的预处理语句相同的方法,并且该方法也返回预期的结果。

我的问题是; 为什么 sql_prepared 查询没有返回任何结果?

import sqlite3

class Database:
    def __init__(self, db: str):
        try:
            self.conn = sqlite3.connect(db)
            self.cursor = self.conn.cursor()
        except sqlite3.Error as e:
            print(e)
            self.__del__

    def fetch_all(self, table: str):
        try:
            query = self.cursor.execute("SELECT * FROM ?", table)
            rows = self.cursor.fetchall()
            return rows
        except sqlite3.Error as e:
            print(e)
            return False

    def fetch_single(self, table: str, column_name: str, column_value):
        sql_formatted_value = "'{value}'".format(value=column_value)
        placeholder = ":{column_name}".format(column_name=column_name)

        sql_insecrue = "SELECT * FROM %s WHERE %s=%s Limit 1" % (
            table, column_name, sql_formatted_value)

        sql_prepared = "SELECT * FROM %s WHERE %s=%s LIMIT 1" % (
            table, column_name, placeholder)

        # try:
        #     self.cursor.execute(sql_insecrue)
        #     rows = self.cursor.fetchall()
        #     return rows
        # except sqlite3.Error as e:
        #     print(e)
        #     return False

        try:
            self.cursor.execute(sql_prepared, [sql_formatted_value, ])
            rows = self.cursor.fetchall()
            return rows
        except sqlite3.Error as e:
            print(e)
            return False

    def insert_single(self, table: str, data: list):
        columns = ""
        placeholders = ""
        values = []
        data_length = len(data)

        for index, (key, value) in enumerate(data):
            # we need to dynamically build some strings based on the data
            # let's generate some placeholders to execute prepared statements
            columns += "{column_name}".format(column_name=key)
            placeholders += ":{column_name}".format(column_name=key)
            # let's fill the insert values into a list to use with execute
            values.append(value)

            # only add a comma if there is another item to assess
            if index < (data_length - 1):
                columns += ', '
                placeholders += ', '

        sql = "INSERT INTO %s (%s) VALUES (%s)" % (
        table, columns, placeholders)

        try:
            self.cursor.execute(sql, values)
            self.conn.commit()
        except sqlite3.Error as e:
            print(e)

您不能使用 ? 替换表名? 在准备好的语句中,因为它不被视为查询参数。

我建议做这样的事情:

self.cursor.execute(f"DELETE FROM {table} WHERE id=?", [id])

换句话说,使用标准的 python 格式语句来指定您的表名,但使用准备好的语句锚,如? 对于任何查询参数。

好的,我发现了问题。

这是我草率的 sql 语法。

在表格和列名周围使用反引号解决了这个问题。

   def fetch_single(self, table: str, column_name: str, column_value):
        sql_formatted_value = "'{value}'".format(value=column_value)
        placeholder = ":{column_name}".format(column_name=column_name)

        sql_insecure = "SELECT * FROM %s WHERE %s=%s" % (
            table, column_name, sql_formatted_value)

        sql_prepared = "SELECT * FROM `%s` WHERE `%s`=%s" % (
            table, column_name, placeholder)

        print(sql_insecure)
        print(sql_prepared)

        # try:
        #     self.cursor.execute(sql_insecure)
        #     row = self.cursor.fetchall()
        #     print(row)
        #     return row
        # except sqlite3.Error as e:
        #     print(e)
        #     return False

        try:
            self.cursor.execute(sql_prepared,
                                [column_value, ])
            row = self.cursor.fetchone()
            return row
        except sqlite3.Error as e:
            print(e)
            return False

暂无
暂无

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

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