【问题标题】:insertion in Postgres database using psycopg2使用 psycopg2 插入 Postgres 数据库
【发布时间】:2019-11-06 15:46:00
【问题描述】:

我正在使用 psycopg2 将数据插入 Postgresql 数据库表 库,但我在插入命令中遇到错误。谁能帮我解决这个问题?

def t_b():  
    table = 'create table {} (Title serial, Link char(50), logo_link 
    char(50), Description Text)'.format(name)  
    cur.execute(table)  
    print("Table created :", name)  

def insertion(name, data):  
    data_s = ",".join(data)
    ins = 'insert into {} (Title,Link,logo_link,Description)values({})'.format(name, data_s)  
    cur.execute(ins)  
    conn.commit()  

def main():  
    t_b("ONE")  
    dd = ('abc', '123', 'INsyustriesz', '<htt:ps>' )  
    insertion("ONE", dd)  

if __name__ == '__main__':  
    main()
    cur.execute()  

并且出现错误信息:

psycopg2.errors.SyntaxError: syntax error at or near ":"  
LINE 1: ... logo_link, Description) values(abc,123,INsyustriesz,htt:ps)

数据没有插入

【问题讨论】:

标签: python-3.x postgresql psycopg2


【解决方案1】:

发生错误是因为您没有在查询的 values 部分中包含单引号。您在 dd 中使用单引号,但这些是为了帮助 Python 将它们解释为字符串。我不建议通过joindata_s 中的所有内容串在一起,但实际上在VALUES 部分中指定每个元素:

    ins = 'insert into {} (Title,Link,logo_link,Description)values({},{},{},{})'.format((name + data))  

【讨论】:

  • 先生,它还没有工作,先生,你能告诉我为什么我们要添加(连接)名称和数据,这个命令也会抛出错误。
猜你喜欢
  • 2020-09-03
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多