python sqlite3插入列表

时间:2017-04-05 20:03:23

标签: python sqlite

我有一个python脚本,应该将列表插入到sqlite表中。看来我的插入语句不起作用。

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

我在命令行检查了数据库但是"服务器"表是空的:

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>

所以看起来实际上没有插入列表。

1 个答案:

答案 0 :(得分:3)

遍历list_并为每个项目执行INSERT。并调用data_entry()来实际插入数据。

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()