Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
1  
Variables are not magically replaced in strings. – tkausl Jun 20 at 20:11
    
You need to pass values not identifiers in values (... – Clodoaldo Neto Jun 20 at 20:13

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))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.