python - 通过 psycopg2 将字符串插入 postgresql

标签 python postgresql psycopg2

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

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')

我正在使用 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. 您不需要引用参数占位符 (%s)。 psycopg2 的优秀人员将确保为您正确完成。
  2. executemany() expects a sequence of parameters .

因此,由于您只插入一行,因此您可以使用 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,),])

关于python - 通过 psycopg2 将字符串插入 postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622689/

相关文章:

python - 使 Tkinter Notebook 可拖动到另一个 View

utf-8 - PostgreSQL:仅在出错时记录查询

sql - 在 Postgres 中插入自定义类型的数组

python - 使用 python 和 postgres,execute 函数中的变量?

python - 实现埃拉托斯特尼筛法时出错

python - 如何避免 numpy.exp() 中的溢出

python - 从 bash 脚本调用远程交互式 python 脚本 : Input request lag

postgresql - pgAdmin 4 中的高延迟时间打开包含许多表的数据库

sql - 用于比较列中每个单词开头的索引

python - 将 connection_factory 指定给 SQLAlchemy 的 create_engine()