简体   繁体   中英

how to insert variables into Sqlite3 database

I'm not familiar with SQL(or python to be honest), and i was wondering how to add variables into tables. This is what i tried:

import sqlite3
conn = sqlite3.connect('TESTDB.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table(number real, txt text)''')
r=4
c.execute('''INSERT INTO table(r,'hello')''')
conn.commit()
conn.close()

This doesn't work.I get the error, "TypeError: 'str' object is not callable"How do i make the table insert the variable r??

Thanks

You have to bind values to placeholders in a prepared statement. See examples in the documentation .

Trying to build a query string on the fly with unknown values inserted directly in it is a great way to get a SQL injection attack and should be avoided.

Your problem is that you don't inject r properly into your query. This should work:

c.execute('''INSERT INTO table(''' + str(r) + ''','hello')''')

cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM