There is such a code:

import sqlite3 import sys big = 'other' string = 'ok' con = sqlite3.connect('aa.db') cur = con.cursor() cur.execute("INSERT INTO posts VALUES (NULL, big, 'default', '', 'no', string, '0')") con.commit() con.close() 

When executed, it gives an error:

 sqlite3.OperationalError: no such column: big 

The error appears to be due to the variables 'big' and 'string'.

Can I do something like adding lines to the sqlite3 database using these variables?

  • one
    cur.execute("INSERT INTO posts VALUES (NULL, ?, 'default', '', 'no', ?, '0')", (big, string)) - Eduard Izmalkov

2 answers 2

In order to create queries to the database for security purposes, it is always recommended to use placeholder . In the sqlite3 module sqlite3 for this, instead of variables, characters of a question mark ( ? ) ? placed in the query text, or a named placeholder , and the execute method passes the second parameter with a list of substituted variables for the first case, or a dictionary for the second.

Question mark example:

 cur.execute("INSERT INTO posts VALUES (NULL, ?, 'default', '', 'no', ?, '0')", (big, string)) 

Example using named placeholders

 cur.execute("INSERT INTO posts VALUES (NULL, :big, 'default', '', 'no', :string, '0')", {"big": big, "string": string}) 

Updated from the @jfs comment

If in the second case the names of the variables coincide with the names of the named placeholder , then the second parameter can be passed to the vars dictionary

 big = 'other' string = 'ok' cur.execute("INSERT INTO posts VALUES (NULL, :big, 'default', '', 'no', :string, '0')", vars()) 
  • In order not to write a dictionary with your hands, you can simply vars() in the example with named parameters. - jfs
  • Thanks, everything worked out - leonidtime

You have big and string are obtained as just words within the query string. You can use format to substitute their values ​​into the query.

Instead of the line where the query is executed, put these two lines:

 query = "INSERT INTO posts VALUES (NULL, {}, 'default', '', 'no', {}, '0')".format(big, string) cur.execute(query) 
  • no such column: other - andreymal
  • So in quotes it is necessary: VALUES (NULL, '{}', 'default', '', 'no', '{}', '0') - aleks.andr
  • @ aleks.andr big = "ot'her" and everything is sad again :) - andreymal
  • do not use string formatting to create sql query. Pass better as parameters. - jfs
  • Thanks, everything worked out - leonidtime