我是python的新手,并且正在使用psycopg2在postgres数据库中插入数据。 我试图插入项目但收到错误消息
“Psycopg2.ProgrammingError:语法错误在”杯子“或附近第1行:插入存储值(7,10.5,咖啡杯)
与咖啡杯旁边的^。 我假设订单错了,但我认为你可以这样输入它,只要你指定了值。
这是代码。
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')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')最满意答案
请记住始终使用execute命令的第二个参数来传递变量,如此处所述。
另外,使用语法中的字段名称:
cur.execute("INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);", (item, quantity, price))这应该够了吧。
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.
更多推荐
发布评论