Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python psycogp2 inserting into postgresql help

I have the following code to insert do an insert into my postgresql database

conn = psycopg2.connect("my connection setting are in here")
cur = conn.cursor()
cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % (1441, "concert", item['title'], item['artists'] )) 

However when I run this I get the following error:

psycopg2.ProgrammingError: column "concert" does not exist
LINE 1: ...(location_id, catname, title, name) VALUES (1441, concert, "...

But "concert" is not a column it is a value so I dont understand why I am getting this error.

EDIT - I have tried putting \" round the value concert and tried without

How can I get my data inserted with out getting this error?

like image 807
Jim Jeffries Avatar asked Nov 06 '10 16:11

Jim Jeffries


People also ask

Does psycopg2 need PostgreSQL?

Prerequisites. The current psycopg2 implementation supports: Python versions from 3.6 to 3.11. PostgreSQL server versions from 7.4 to 15.

How does Python connect to Postgres database?

How to Connect to PostgreSQL from Python? In order to connect to a PostgreSQL database instance from your Python script, you need to use a database connector library. In Python, you have several options that you can choose from. Some libraries that are written in pure Python include pg8000 and py-postgresql.


1 Answers

You really, really shouldn't use python string formatting to build queries - they are prone to SQL injection. And your actual problem is that you use " for quoting while you have to use ' for quoting (" quotes table/column names etc, ' quotes strings).

Use the following code instead:

cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%s, %s, %s, %s)', (1441, 'concert', item['title'], item['artists']))

Note that you have to use %s no matter what type you actually have.

Also see http://initd.org/psycopg/docs/usage.html#query-parameters.

like image 136
ThiefMaster Avatar answered Sep 18 '22 01:09

ThiefMaster