简体   繁体   中英

Insert values from list into table (Python, sqlite3)

I have this simple code which I can't make work.

import sqlite3

conn = sqlite3.connect('db\\books')
c = conn.cursor()

col = []

title = input('title')
text = input('text')
tags = input('tags')

col.append(title)
col.append(text)
col.append(tags)

c.executescript("INSERT INTO books (title,text,tags) "
                "VALUES (col[0],col[1],col[2])")

The db code (connection and normal insert) works but the problem rise when I want to do what you see above.

The goal I would like to achieve is to let the user insert the data into db (all strings). I don't know if this is the right way to do this...

How can I do this ?

Thanks

This line:

c.executescript("INSERT INTO books (title,text,tags) "
                "VALUES (col[0],col[1],col[2])")

Is not a valid SQL. Now since c is defined as a cursor, you can run execute from it directly instead of executescript , which the latter is suppose to create a cursor from a connection and execute a SQL. Just replace that line with the following should work:

c.execute("INSERT INTO books (title,text,tags) "
          "VALUES (?,?,?)", col)

The SQL above uses a "qmark style" placeholder, which takes actual value from the parameter list that follows it.

One option is to change your last line to:

c.execute("INSERT INTO books (title,text,tags) VALUES (?,?,?)", (col[0], col[1], col[2]))

And then commit and close the connection if you're done making changes:

conn.commit()
conn.close()

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