Reputation: 57
I have a query which should insert the contents of a list to a table. It's my understanding that each %s should be replaced by the content of the valueInsert list I've added to the execute command.
However I get the following error
c.executemany(test4, valuesInsert)
sqlite3.OperationalError: near "%": syntax error
Query:
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)"
Command to execute query
c.executemany(test4, valuesInsert)
Contents of List:
['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']
Upvotes: 0
Views: 112
Reputation: 142651
executemany
doesn't mean many arguments in one INSERT
.
executemany
is used when you have list of lists - data for many rows in database - and you want to execute many INSERT
valuesInsert = [
['Norwell',... ],
['Other Place', ...],
]
c.executemany(test4, valuesInsert)
but you have only one element - data for one row in database - and you want to execute only one INSERT
so you should use execute()
valuesInsert = ['Norwell',... ]
c.execute(test4, valuesInsert)
BTW: when you use ['Norwell',... ]
with executemany
then it get 'Norwell'
as data for first row (for first INSERT
) and threat string as list of chars.
valuesInsert = [
['N', 'o', 'r', 'w', 'e', 'l', 'l']
]
Because 'Norwell'
has 7 chars so it see 7 elements and you get message The current statement uses 17, and there are 7 supplied
.
Upvotes: 1
Reputation: 2094
I hope this code can help you (this example just use columns type text)
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)
Upvotes: 0