user1793606 user1793606 - 1 year ago 85
Python Question

Inconsistent SQLite3 insert from Python 2.7

I have an issue inserting values into SQLite3 database from Python. The following code inserts the new line differently.

m.execute("INSERT INTO transactions VALUES "+str((timestamp,address,recipient_input,amount_input,signature_enc,public_key_readable,openfield_input))+"")

m.execute("INSERT INTO transactions VALUES ('" + str(timestamp) + "','" + str(address) + "','" + str(recipient_input) + "','" + str(amount_input) + "','" + str(signature_enc) + "','" + str(public_key_readable) + "','" +str(openfield_input) + "')")

The second example inserts new lines properly into the SQLite database, the first one inserts "\n" symbol. Is there any explanation for that? I would like to use the first model using tuples, but without replacing the new lines with "\n" symbol.

Answer Source

str() formats its argument according to the Python syntax rules, so it is never appropriate for SQL.

To prevent formatting problems (and SQL injection attacks), use parameters:

m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?)",
          (timestamp, address, recipient_input, amount_input,
           signature_enc, public_key_readable, openfield_input))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download