Python cur.executemany不能在字符串格式化期间转换所有参数
我有下面的函数,它应该批量插入IPv6 IP的列表Python cur.executemany不能在字符串格式化期间转换所有参数,python,psycopg2,Python,Psycopg2,我有下面的函数,它应该批量插入IPv6 IP的列表 def insertToDb(ipList): print("OK") try: conn = psycopg2.connect("dbname='mydb' user='myuser' host='hanno.db.elephantsql.com' password='mypass'") except: print("I am unable to connect to the database") cur =
def insertToDb(ipList):
print("OK")
try:
conn = psycopg2.connect("dbname='mydb' user='myuser' host='hanno.db.elephantsql.com' password='mypass'")
except:
print("I am unable to connect to the database")
cur = conn.cursor()
try:
cur.executemany("INSERT INTO ip (ip) VALUES(%s)", ipList)
conn.commit()
except Exception as e: print(e)
print("Inserted!")
我得到以下信息
并非所有参数都在字符串格式化期间转换
所需的正确格式是什么?使用
executemany
,您可能只需要将ipList
转换为元组列表,如下所示:
params = [(ip,) for ip in iplist]
cur.executemany("INSERT INTO ip (ip) VALUES(%s)", params)
或者,您也可以将构建列表的方式更改为:
ipList.append((address,))
ipList应该是一个包含值的元组列表我想我已经将它作为一个元组列表了,下面是我如何创建列表ipList=[],然后用ipList添加IP。在循环中追加(地址),然后调用insertToDb(ipList)