ALI AHMAD
ALI AHMAD

Reputation: 33

insertion in Postgres database using psycopg2

I am inserting data into Postgresql database table by using psycopg2 library, but I am getting an error in the insertion command. Can anyone help me to resolve this issue?

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

And the error message appears:

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

and data is not inserted

Upvotes: 2

Views: 69

Answers (1)

richyen
richyen

Reputation: 9958

The error happens because you're not including single-quotes in the values section of the query. You use single-quotes in dd, but those are to help Python interpret them as strings. I wouldn't recommending stringing everything together in data_s via a join, but actually specifying each element in the VALUES section:

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

Upvotes: 1

Related Questions