Sheldon
Sheldon

Reputation: 10077

What is the correct formatting for this sqlite3 query? (Python)

I have the following code:

def add_record(self,values):
    self.sql.execute("INSERT INTO TEST VALUES (?,?)" % values)

and I would like adjust it to accommodate for a user defined table, e.g:

def add_record(self,tablename,values):
        self.sql.execute("INSERT INTO TEST VALUES (?,?)" % values)

However I'm not suer on the correct formatting. Can someone help?

Upvotes: 1

Views: 761

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169284

Be warned that using string-interpolation with any query brings with it the risk of SQL-injection attack.

If you can be sure that malicious code will not be used, you can use the following two-step process.
1. String-interpolation of table name.
2. Pass query parameters as the second argument to .execute()

(Parametrization of table- and/or column-names is not supported.)

def add_record(self, tablename, values):
    the_query = "INSERT INTO {:s} VALUES (?,?);".format(tablename)
    self.sql.execute(the_query, values)

Upvotes: 2

Related Questions