使用cursor.ecute(脚本,参数)[重复]时出现了Python sqlite3语法错误

qyuhtwio  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(158)

这个问题在这里已经有答案

Inserting a table name into a query gives sqlite3.OperationalError: near "?": syntax error(3个答案)
上个月关门了。
我已经创建了一个SQL连接器类,并且有一个带有预设置字符串和一些参数的SELECT函数,但我总是收到这个错误

Traceback (most recent call last):
  File "x:\User Projects\Python.Password.DataBase\in_testing_modules\sqlconnector.py", line 81, in execute
    self.cursor.execute(script, parameters)
sqlite3.OperationalError: near "?": syntax error

班级简化了

import sqlite3 # not sure if I need show this

class SqlConnector:
    def __init__(self) -> None:
        self.connection = None
        self.cursor = None

    def connect(self, database):
        try:
            with sqlite3.connect(database) as db:
                self.connection = db
                self.cursor = self.connection.cursor()
        except (TypeError, Exception) as e:
            logging.exception(msg=e)

    def execute(self, script: str = "", parameters: tuple = None):
        try:
            if parameters:
                self.cursor.execute(script, parameters)
            else:
                self.cursor.execute(script)
        except (TypeError, ValueError, sqlite3.OperationalError, Exception) as e:
            logging.exception(msg=e)

    def select(self, selection: str = "*", table: str = "Table", where: list | tuple = None):
        self.execute(
            script="SELECT ? FROM ?", parameters=(selection, table,))

错误的复制

sql = SqlConnector()
    sql.connect(":memory:")

    sql.execute("""CREATE TABLE IF NOT EXISTS test(Account TEXT NOT NULL)""")
    acc = Account(username="SUPERMAN", password="Secure4321") # Account is a separate class
    sql.execute("INSERT INTO test (Account) VALUES(?)", (acc,))
    sql.commit()

    sql.select(selection="*", table="test")
    retur = sql.fetchall()
    print(retur)

如果帖子有什么遗漏,请告诉我

s1ag04yj

s1ag04yj1#

不能使用参数绑定来代替数据库对象标识符,例如列名和表名。您只能执行SELECT bla FROM qqq WHERE bla = ?。您不能在此处将blaqqq替换为?

相关问题