将python列表插入SQLite数据库

问题描述 投票:1回答:2

我有一个查询,应该将列表的内容插入到表中。据我了解,每个%s都应替换为我添加到execute命令中的valueInsert列表的内容。

但是出现以下错误

c.executemany(test4,valuesInsert)

sqlite3.OperationalError:在“%”附近:语法错误

查询:

test4 = "INSERT INTO test (city,region_code,os,ip,isp,area_code,\
    dma_code,last_update,country_code3,country_name,postal_code,\
        longitude,country_code,ip_str,latitude,org,asn) VALUES \
            (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"

执行查询的命令

c.executemany(test4, valuesInsert)

列表内容:

['Norwell', 'MA', None, 1572395042, 'EdgeCast Networks', 781, 506, '2019-12-09T00:44:43.812333', 'USA', 'United States', '02061', -70.8217, 'US', '93.184.216.34', 42.15960000000001, 'Verizon Business', 'AS15133']
python sqlite
2个回答
0
投票

executemany并不意味着一个INSERT中有很多参数。

[executemany用于列表列表-数据库中许多行的数据-并且要执行许多INSERT

valuesInsert = [ 
   ['Norwell',... ], 
   ['other place', ...], 
]


c.executemany(test4, valuesInsert)

但是您只有一个元素-数据库中一行的数据-并且您只想执行一个INSERT,因此您应该使用execute()

valuesInsert = ['Norwell',... ]

c.execute(test4, valuesInsert)

BTW:当您将['Norwell',... ]executemany一起使用时,它会以'Norwell'作为第一行的数据(用于第一个INSERT),并将其用作字符列表-因为它有7个字符,所以它可以看到7个元素。


0
投票

我希望这段代码可以为您提供帮助(此示例仅使用列类型的文本)

import sqlite3
con = sqlite3.connect("samples.db")
cur = con.cursor()

cmd = "CREATE TABLE IF NOT EXISTS test2 (city text,region_code text,os text,ip text,isp text,area_code text, dma_code text,last_update text,country_code3 text,country_name text,postal_code text, longitude text,country_code text,ip_str text ,latitude text,org text ,asn text)"
cur.execute(cmd)

list1 = ['Norwell', 'MA', None, 1572395042, 'EdgeCast Networks', 781, 506, '2019-12-09T00:44:43.812333', 'USA', 'United States', '02061', -70.8217, 'US', '93.184.216.34', 42.15960000000001, 'Verizon Business', 'AS15133']
list2 = ['Norwell', 'MA', None, 1572395042, 'EdgeCast Networks', 781, 506, '2019-12-09T00:44:43.812333', 'USA', 'United States', '02061', -70.8217, 'US', '93.184.216.34', 42.15960000000001, 'Verizon Business', 'AS15133']

con.executemany("INSERT INTO test2(city,region_code,os,ip,isp,area_code, dma_code,last_update,country_code3,country_name,postal_code, longitude,country_code,ip_str,latitude,org,asn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (list1, list2))

for row in cur.execute("SELECT * FROM test2"):

    print (row)
© www.soinside.com 2019 - 2024. All rights reserved.