我有以下功能,可以批量插入 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 = conn.cursor()
try:
cur.executemany("INSERT INTO ip (ip) VALUES(%s)", ipList)
conn.commit()
except Exception as e: print(e)
print("Inserted!")
我收到以下消息
not all arguments converted during string formatting
需要什么样的正确格式?
请您参考如下方法:
使用 executemany,您可能只需要将 ipList 转换为元组列表,如下所示:
params = [(ip,) for ip in iplist]
cur.executemany("INSERT INTO ip (ip) VALUES(%s)", params)
或者您也可以将构建列表的方式更改为:
ipList.append((address,))
