使用 psycopg2 插入 Postgres 数据库

insertion in Postgres database using psycopg2

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

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)

并且没有插入数据

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

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