0

Using SQLite3, how do you use multiple variables in one request? Using one works but once you add a second it gives you the syntax error below. I have tried researching this and I cannot find any documentation/other questions in the same situation.

Code:

self.db.execute("INSERT INTO complements (:record) VALUES (:field)", {"record": record, "field": field})

Error:

|Traceback (most recent call last):
  File "(path)", line 22, in <module>
    db.add("Adjective", "adjective")
  File "(path)", line 17, in add
    self.db.execute("INSERT INTO complements (:record) VALUES (:field)", {"record": record, "field": field})
sqlite3.OperationalError: near ":record": syntax error
2
  • Pretty sure you can't parameterize column names, only values. You'll have to use format strings to parameterize the query. Take care to prevent SQL injection! Commented May 25, 2022 at 10:55
  • Are there any other ways to parameterize them? I could create different functions but I'd prefer one Commented May 25, 2022 at 10:58

1 Answer 1

1

Column names (and other identifiers like table names) can't be parameterized which is why you are getting a syntax error. Only "values" (the data to be inserted) can be parameterized. To fix this, format the query yourself, for example using format strings:

record, field = ...
self.db.execute(f"INSERT INTO complements ({record}) VALUES (:field)", {"field": field})

if record is user-provided you must take care to prevent SQL injection, e.g. by checking whether it is a valid column name: record in ["some", "column", "names"]; it is however rather uncommon to parameterize identifiers in queries, so this feels like an XY-Problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.