简体   繁体   中英

Postgresql insert data error when using python

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM