2012-03-08 86 views
1

我想插入一些字符串值到postgresql數據庫中。即:通過pyscopg2插入字符串到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,)) 

回答

3

那裏有幾個問題:

  1. 您不需要引用參數佔位符(%s)。 psycopg2的好人將確保爲你做好。
  2. executemany()expects a sequence of parameters

所以,因爲你只插入一個一行,你可以只使用​​:

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,),])