将python列表插入SQLite数据库

2024-10-02 06:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个查询,它应该将列表的内容插入到表中。我的理解是,每个%s都应该替换为我添加到execute命令的valueInsert列表的内容。你知道吗

但是我得到以下错误

c.executemany(test4, valuesInsert)

sqlite3.OperationalError: near "%": syntax error

查询:

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']

Tags: 命令ip内容列表execute错误codecountry
2条回答

executemany并不意味着一个INSERT中有许多参数。你知道吗

executemany当您拥有列表列表(数据库中许多行的数据)并且希望执行许多INSERT时使用

valuesInsert = [ 
    ['Norwell',... ], 
    ['Other Place', ...], 
]


c.executemany(test4, valuesInsert)

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

valuesInsert = ['Norwell',... ]

c.execute(test4, valuesInsert)

顺便说一句:当您将['Norwell',... ]executemany一起使用时,它将'Norwell'作为第一行的数据(对于第一行INSERT)和威胁字符串作为字符列表。你知道吗

valuesInsert = [ 
    ['N', 'o', 'r', 'w', 'e', 'l', 'l'] 
]

因为'Norwell'有7个字符,所以它可以看到7个元素,然后得到消息The current statement uses 17, and there are 7 supplied。你知道吗

希望这段代码能对您有所帮助(本例只使用列类型文本)

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)

相关问题 更多 >

    热门问题