Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python psycopg2 syntax error

I am new to python and working on using the psycopg2 to insert data in postgres database. I am trying to insert items but get the error message

"Psycopg2.ProgrammingError: syntax error at or near "cup" LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup)

with the ^ next to coffee cup. I am assuming the order is wrong but i thought you could enter it this way as long as you specified the values.

Here is the code.

import psycopg2

def create_table():
    conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
    cur=conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
    conn.commit()
    conn.close()

def insert(quantity, price, item):
    conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
    cur=conn.cursor()
    cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
    conn.commit()
    conn.close()

create_table()
insert(7, 10.5, 'coffee cup')
like image 909
IpSp00f3r Avatar asked Oct 21 '25 11:10

IpSp00f3r


2 Answers

Remember to always use the second argument of the execute command to pass the variables, as stated here.

Also, use the name of the fields in your syntax:

cur.execute("INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);", (item, quantity, price))

That should do the trick.

like image 108
jgmh Avatar answered Oct 24 '25 01:10

jgmh


Problem in your case is coffee cup parameter value is considered as string but psycopg2 accept the value in single quote. Basically as per my understanding when we create SQL query for psycopg2 it ask for single quote for data parameters [if you have given double quote for query start and end] In your case you have given double quote for Query Start and end so you need to give single quote for the parameters.


My Observation is you provide single quote for each data paramater in psycopg2


import psycopg2

def create_table():
    conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
    cur=conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
    conn.commit()
    conn.close()

def insert(quantity, price, item):
    conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
    cur=conn.cursor()
    #cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
    cur.execute("INSERT INTO store VALUES('%s','%s','%s')" % (quantity, price, item))
    conn.commit()
    conn.close()

create_table()
insert(7, 10.5, 'coffee cup')
like image 42
Vardhman Patil Avatar answered Oct 24 '25 01:10

Vardhman Patil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!