Python psycopg2语法错误(Python psycopg2 syntax error)

编程入门 行业动态 更新时间:2024-10-26 13:23:49
Python psycopg2语法错误(Python psycopg2 syntax error)

我是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.

更多推荐

本文发布于:2023-07-29 18:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1318673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法错误   Python   syntax   error

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!