【问题标题】:Using INSERT with a PostgreSQL Database using Python使用 Python 将 INSERT 与 PostgreSQL 数据库一起使用
【发布时间】:2012-02-22 22:11:28
【问题描述】:

我正在尝试使用 Python 将数据插入到 PostgreSQL 数据库表中。我没有看到任何语法错误,但由于某种原因,我的数据没有插入到数据库中。

conn = psycopg2.connect(connection)
cursor = conn.cursor()
items = pickle.load(open(pickle_file,"rb"))

for item in items:
    city = item[0]
    price = item[1]
    info = item[2]

    query =  "INSERT INTO items (info, city, price) VALUES (%s, %s, %s);"
    data = (info, city, price)

    cursor.execute(query, data)

【问题讨论】:

  • 必须提交数据,如 conn.commit()
  • 对于字符串插值,您现在可以使用:('{0}', '{1}', '{2}') 代替上面的 (%s, %s, %s)。

标签: python postgresql psycopg2


【解决方案1】:

你必须提交事务。

conn.commit()

如果没有理由认为事务会失败,那么在 for 循环完成后提交会更快。

【讨论】:

  • np,我总是犯同样的错误 ;)
猜你喜欢
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多