-1

I am trying to insert data to the table that was created earlier using python script. Here is the code I am trying to execute. I want to insert data into table with date as well.

date_today = dt.date.today()

conn = psycopg2.connect(host = serverip, port = port, database = database,    user = uid, password = pwd)
cursor = conn.cursor()

cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")

print "Data Inserted successfully"
conn.commit()
conn.close()

Here is the error I see from my job. what am i missing here?

psycopg2.ProgrammingError: column "date_today" does not exist

I created the table using different job with the following query:

cursor.execute("""CREATE TABLE MY_TABL(Date date, Lob varchar(30), Total_Students int, failed_students int, Percent_passed_students int)""")

And the table is created with above five columns.

2
  • 1
    Variables are not magically replaced in strings. Commented Jun 20, 2016 at 20:11
  • You need to pass values not identifiers in values (... Commented Jun 20, 2016 at 20:13

1 Answer 1

3

This line:

cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")

Is the incorrect way to dynamically insert values into a database.


Here's a functional and correct example:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

And applying it in your case...

cursor.execute("INSERT INTO My_TABLE VALUES (%s, %s, %s, %s, %s)", (date_today, 'Class Name', int1, int2, int3))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.