views:

146

answers:

2

How can you fix this SQL-code?

My Python code:

import os, pg, sys, re, psycopg2                                              

conn = psycopg2.connect("dbname=tk user=masi password=123")
cur = conn.cursor() 
cur.execute("""INSERT INTO courses ('course_nro')
    VALUES ( `:1` )""", ['hen'])

I get:

Traceback (most recent call last):                                            
  File "<stdin>", line 13, in <module>
psycopg2.ProgrammingError: syntax error at or near "'course_nro'"
LINE 1: INSERT INTO courses ('course_nro')
                             ^
+1  A: 

Remove the quotes around the fieldname:

INSERT INTO courses (course_nro)
truppo
You also need to remove the backticks around the `:1` parameter.
bobince
+2  A: 

You made 3 different errors in the same query:

  1. Field names should not be quoted.
  2. psycopg2 uses tuples, not lists for arguments.
  3. Positional arguments like ":1" are not supported.

Change your query into:

cur.execute("""INSERT INTO courses (course_nro) VALUES (%s)""", ('hen',))

fog