pymysql.err.OperationalError:1054。“‘where 子句’中的未知列‘X’

问题描述 投票:0回答:2

我在控制台中收到以下错误,其中列名称实际上是通过查询传递的值:

pymysql.err.OperationalError:(1054,“未知列“LiqNac83437” 'where 子句'")

这是我的职责:

sql = f"""
            SELECT 
                detallev.clave,
                detallev.cantidad,
                venta.fecha
            FROM
                detallev
                    INNER JOIN
                venta ON detallev.ven_id = venta.ven_id
            WHERE
                clave = '{codigoBarras}'
            AND (fecha BETWEEN {fecha_inicio} AND {fecha_final});"""
    print(sql)
    with bd:
        with bd.cursor() as cursor:
            cursor.execute(sql)
            resultado = cursor.fetchall()
            cursor.close()

调用者:

@app.get('/{sucursal}/reporte/articulos/')
def reporte_articulo(sucursal: Origenes, clave: str = '', fecha_inicial: str = '', fecha_final: str = fechaHoy(), username: str = Depends(valida_usuario)):
    return reporte_articulos.reporte_articulo(sucursal, clave, fecha_inicial, fecha_final)

我正在使用 FastAPI、python 和 Mysql。 我已经尝试过遵循这些解决方案,但没有成功:

解决方案1 解决方案2

以及 stackoverflow 之外的其他几个解决方案,已经尝试以不同类型的方式包装连接值。

  • 当直接在 Mysql 工作台上运行此查询时,除了从 API 调用它之外,它工作得非常完美。
  • 当传递给函数的列名值只是数字“47839234215”而不是“LiqNac83437”(数字和字母)时,它的效果正如预期的那样好。
python mysql fastapi pymysql
2个回答
1
投票

发生这种情况是因为您自己替换了值,在这种情况下,您没有正确引用

BETWEEN
子句中的字段。 它看到
LiqNac83437
并认为它是一个列名称,因为它没有被引用。

出于这个原因,为了避免 SQL 注入问题,您应该让数据库连接器进行引用:

    sql = """
            SELECT 
                detallev.clave,
                detallev.cantidad,
                venta.fecha
            FROM
                detallev
                    INNER JOIN
                venta ON detallev.ven_id = venta.ven_id
            WHERE
                clave = ?
            AND fecha BETWEEN ? AND ?;"""
    with bd.cursor() as cursor:
        cursor.execute(sql, (codigoBarras, fecha_inicio, fecha_final))
        resultado = cursor.fetchall()
        cursor.close()

0
投票

我在 erpnext 15 中遇到了类似的错误

pymysql.err.OperationalError:(1054,“'where子句'中的未知列'tabLoan.repay_from工资'”)可能的错误来源:hrms(app)

然后我尝试了下面的命令,工作正常后......

基准执行hrms.setup.after_install

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.