Inserting strings into postgresql through pyscopg2

怎甘沉沦 提交于 2019-12-12 22:41:58

问题


I'm trying to insert some string values into a postgresql db. namely:

macaddress,
timestamp (date time format)
type of device (string)
subtype (string)

example:

INSERT INTO device (address, tstamp, type, subtype) 
     VALUES ('00:00:00:00','2012-02-22 19:31:26','computer','notebook')

I'm using python psycopg2 script to dump the data and the following error is appearing:

c.executemany("INSERT INTO device VALUES (default, '%s','%s','%s','%s')", 
              (mac, date, typedev, subtype,))
TypeError: not all arguments converted during string formatting

the command I'm using to insert is:

c.executemany("INSERT INTO device VALUES (default, '%s','%s','%s','%s')", 
              (mac, date, typedev, subtype,))

回答1:


There are a couple of problems:

  1. You don't need to quote the parameter placeholders (%s). The good people of psycopg2 will ensure that is done properly for you.
  2. executemany() expects a sequence of parameters.

So since you're only inserting one row you could just use execute():

c.execute("INSERT INTO device VALUES (default,%s,%s,%s,%s)", 
          (mac, date, typedev, subtype,))

When you need to use executemany() remember to pass it a sequence of parameters, e.g.:

c.executemany("INSERT INTO device VALUES (default,%s,%s,%s,%s)", 
              [(mac, date, typedev, subtype,),])


来源:https://stackoverflow.com/questions/9622689/inserting-strings-into-postgresql-through-pyscopg2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!