Python sqlite3 syntax error with cursor.execute(script, arguments)

Question:

I have made a sql connector class and I have a select function with a pre-set string and some parameters
but I keep getting this error

Traceback (most recent call last):
  File "x:User ProjectsPython.Password.DataBasein_testing_modulessqlconnector.py", line 81, in execute
    self.cursor.execute(script, parameters)
sqlite3.OperationalError: near "?": syntax error

The class simplified

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,))

Replication of error

    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)

If something about the post is missing please tell me

Asked By: r8gobb8

||

Answers:

You CANNOT use parameter binding in place of database object identifiers, such as column and table names. You can only do SELECT bla FROM qqq WHERE bla = ?. You cannot replace bla or qqq here with ?.

Answered By: PChemGuy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.