【问题标题】:Python psycopg2 syntax errorPython psycopg2 语法错误
【发布时间】:2017-12-03 19:53:38
【问题描述】:

我是 python 新手,正在使用 psycopg2 在 postgres 数据库中插入数据。我正在尝试插入项目,但收到错误消息

“Psycopg2.ProgrammingError:在“cup”处或附近出现语法错误 LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup)

在咖啡杯旁边带有 ^。我假设顺序是错误的,但我认为只要你指定了值,你就可以这样输入。

这里是代码。

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

【问题讨论】:

  • 不要在sql查询中直接做字符串插值。它使您容易受到sql injection attacks 的攻击。在这种情况下,它还会导致您的查询格式不正确。
  • 谢谢保罗。我对 python 和 psycopg2 非常陌生,并且正在关注网络上的示例以了解事物的工作原理。在这种情况下,您将如何避免上述代码中的 SQL 注入? Psycocg2 文档建议无论传递什么类型的数据,都应该使用 %s。任何帮助将不胜感激。

标签: python postgresql


【解决方案1】:

请记住始终使用执行命令的第二个参数来传递变量,如here 所述。

另外,在语法中使用字段的名称:

cur.execute("INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);", (item, quantity, price))

这应该可以解决问题。

【讨论】:

  • 这就像一个魅力。感谢您为我指明正确的方向
【解决方案2】:

您的问题是 咖啡杯 参数值被视为字符串,但 psycopg2 接受单引号中的值。 基本上根据我的理解,当我们为 psycopg2 创建 SQL 查询时,它要求数据参数使用单引号 [如果您为查询开始和结束提供了双引号] 在您的情况下,您为查询开始和结束提供了双引号,因此您需要为参数提供单引号。


我的观察是您为 psycopg2 中的每个数据参数提供单引号


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))
    cur.execute("INSERT INTO store VALUES('%s','%s','%s')" % (quantity, price, item))
    conn.commit()
    conn.close()

create_table()
insert(7, 10.5, 'coffee cup')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2021-09-28
    • 2018-03-12
    • 2020-11-18
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多