【问题标题】:Failed to insert into postgresql table无法插入到 postgresql 表中
【发布时间】:2013-08-15 07:36:46
【问题描述】:

我正在使用它来创建表:

dbconn=psycopg2.connect("dbname='postgres' host='localhost' port='5432' user='postgres' password='123456'")
cur=dbconn.cursor()
cur.execute("""
CREATE TABLE Person
(
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
""")

但是当我尝试用这个插入数据库时​​:

>>> cur.execute("""INSERT INTO Persons (LastName,FirstName,Address,City) VALUES ('%s','%s','%s','%s');""",("aa","bb","cc","dd"))

这是我得到的:

Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    cur.execute("""INSERT INTO Persons (LastName,FirstName,Address,City) VALUES ('%s','%s','%s','%s');""",("aa","bb","cc","dd"))
ProgrammingError: syntax error at or near "aa"
LINE 1: ...rsons (LastName,FirstName,Address,City) VALUES (''aa'',''bb'...

【问题讨论】:

  • 您需要使用dbconn.commit() 提交您的事务,否则您的表将不会被创建。
  • @BurhanKhalid 试过了!但它不起作用!

标签: python postgresql python-2.7


【解决方案1】:

不应该这样吗?

cur.execute("INSERT INTO Persons (LastName,FirstName,Address,City) VALUES (%s, %s, %s, %s);", ("aa", "bb", "cc", "dd"))

来自psycopg documentation的示例:

>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
...      (100, "abc'def"))

【讨论】:

  • 还是不行! :(Traceback (most recent call last): File "&lt;pyshell#13&gt;", line 1, in &lt;module&gt; cur.execute("INSERT INTO Person (LastName,FirstName,Address,City) VALUES (%s, %s, %s, %s);", ("aa", "bb", "cc", "dd")) InternalError: current transaction is aborted, commands ignored until end of transaction block
猜你喜欢
  • 2022-01-27
  • 2021-06-12
  • 2016-03-02
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 2014-04-17
相关资源
最近更新 更多