通过psycopg2将字符串插入postgresql

时间:2012-03-08 18:18:13

标签: python postgresql psycopg2

我正在尝试将一些字符串值插入到postgresql数据库中。即:

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

示例:

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

我正在使用python psycopg2脚本转储数据,并出现以下错误:

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

我用来插入的命令是:

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

1 个答案:

答案 0 :(得分:3)

有几个问题:

  1. 您不需要引用参数占位符(%s)。 psycopg2的好人将确保为您做好。
  2. executemany() expects a sequence of parameters
  3. 因此,您只需插入一行,就可以使用execute()

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

    当您需要使用executemany()时,请记住将一系列参数传递给它,例如:

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