For some reason I am getting errors when using placeholders in select
statements.
def get_id(table_name, id_name):
db = sqlite3.connect('test_db')
max_id = db.execute('''SELECT max(?) FROM ?''', (id_name, table_name)).fetchone()[0]
if not max_id:
primary_id = 0
else:
primary_id = max_id + 1
This functions returns this error:
File "test.py", line 77, in get_id
max_id = db.execute('''SELECT max(?) FROM ?''', (id_name, table_name)).fetchone()[0]
sqlite3.OperationalError: near "?": syntax error
Python SQLite fetchone The fetchone returns the next row of a query result set, returning a single tuple, or None when no more data is available.
Each open SQLite database is represented by a Connection object, which is created using sqlite3.connect() . Their main purpose is creating Cursor objects, and Transaction control. An SQLite database connection has the following attributes and methods: cursor (factory=Cursor)
SQLite Python: Querying Data First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.
First, connect to the SQLite database by creating a Connection object. Second, create a Cursor object by calling the cursor method of the Connection object. Third, execute an INSERT statement. If you want to pass arguments to the INSERT statement, you use the question mark (?) as the placeholder for each argument.
You aren't able to use placeholders for column or table names. The placeholders are for values used to insert or retrieve data from the database. The library properly sanitizes them.
To do what you want, try something like this:
db.execute('''SELECT max({}) FROM {}'''.format(id_name, table_name)).fetchone()[0]
This will use string formatting to build your query. If you need to add a WHERE
condition to this, you can still do that using parameters:
db.execute('''SELECT max({}) FROM {} WHERE ID = ?'''.format(id_name, table_name), id_variable).fetchone()[0]
You're seeing this error because placeholders can only be used to substitute values, not column or table names.
In this case, you will have to use Python's string formatting, being very careful that the values don't contain SQL or special characters:
max_id = db.execute(
'SELECT max(%s) FROM %s where foo > ?' %(id_name, table_name),
(max_foo_value, ),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With