Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sqlite3 insert list

Tags:

python

sqlite

I have a python script that should insert a list into a sqlite table. It appears my insert statement is not working.

links = ['a', 'b', 'c']

conn = sqlite3.connect('example.db')

#create a data structure
c = conn.cursor()

#Create table
c.execute('''Create TABLE if not exists server("sites")''')

#Insert links into table
def data_entry():
    sites = links
    c.execute("INSERT INTO server(sites) VALUES(?)", (sites))
    conn.commit()

#query database
c.execute("SELECT * FROM server")
rows = c.fetchall()
for row in rows:
    print(row)

conn.close

I checked the database at command line but the "server" table is empty:

C:\App\sqlite\sqlite_databases>sqlite3
SQLite version 3.17.0 2017-02-13 16:02:40
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .tables
server
sqlite> SELECT * FROM server
...> ;
sqlite>

So it doesn't appear that the list is actually being inserted.


1 Answers

Iterate over list_ and execute INSERT for each item. And call data_entry() to actually insert data.

import sqlite3

list_ = ['a', 'b', 'c']

#create a data structure
conn = sqlite3.connect('example.db')
c = conn.cursor()

#Create table
c.execute('''Create TABLE if not exists server("sites")''')

#Insert links into table
def data_entry():
    for item in list_:
        c.execute("INSERT INTO server(sites) VALUES(?)", (item,))
    conn.commit()

data_entry()  # ==> call the function

#query database
c.execute("SELECT * FROM server")
rows = c.fetchall()
for row in rows:
    print(row)

conn.close()
like image 180
Dušan Maďar Avatar answered Sep 13 '25 08:09

Dušan Maďar