简体   繁体   中英

Why does this SQL query fail?

I have a database class which abstracts some basic crud logic.

The issue lies in the fetch_single method:

The sql_insecure query works fine, and returns the expected results.

The sql_prepared query doesn't return any errors, but also doesn't return any results which match the parameters, when they clearly do exist within the db.

sql_prepared follows the same approach to prepared statements that the insert_single method implements, and this method also returns the expected results.

My question is; why is the sql_prepared query not returning any results?

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)

You cannot substitute table name using ? in prepared statements because it is not considered a query parameter.

I recommend doing something like this:

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

In other words, use standard python format statements to specify your table name, but use prepared statement anchors like ? for any query parameters.

okay, i found the problem.

its was my sloppy sql syntax.

using backticks around the table and column name solved the issue.

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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