【问题标题】:SQLAlchemy select with where constraint带有 where 约束的 SQLAlchemy 选择
【发布时间】:2014-10-23 23:48:53
【问题描述】:

我正在尝试从我的数据库中获取一个表的子集。该数据库是一个MySql数据库。

Python 代码:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, VARCHAR, DATETIME, INT, TEXT, TIMESTAMP
from datetime import datetime
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
class TrackablesTable(Base):
        __tablename__ = 'Trackables'

        trackableId = Column(INT, primary_key=True) #autogenerate
        productID = Column(TEXT)
        createdOn = Column(TIMESTAMP) #autogenerate
        urlTitle = Column(TEXT)
        humanTitle = Column(TEXT)
        userId = Column(VARCHAR(45))


        def __repr__(self):
                return "<MyTable(%s)>" % (self.asin)

        @staticmethod
        def getTrackableByProductId(productID, session):
            trackable = session.query(TrackablesTable).filter_by(productID=productID)
            return trackable

注意底部的方法。我期待这种方法可以让我获得“可跟踪”表中的所有行,其中包含带有 productID 变量值的“productID”列。相反,它似乎返回了一个格式错误的查询。

它返回的查询如下:

SELECT "Trackables"."trackableId" AS "Trackables_trackableId", "Trackables"."productID" AS "Trackables_productID", "Trackables"."createdOn" AS "Trackables_createdOn", "Trackables"."urlTitle" AS "Trackables_urlTitle", "Trackables"."humanTitle" AS "Trackables_humanTitle", "Trackables"."userId" AS "Trackables_userId" 
FROM "Trackables" 
WHERE "Trackables"."productID" = :productID_1

MySQL 工作台告诉我查询格式错误。另外,productID(":productID_1")的查询值并不是代码中引用的变量的实际值。

【问题讨论】:

  • :productID_1 不是一个值,它是一个占位符,将绑定到传递给execute 函数的参数。这就是避免Little Bobby Tables eating your database 的方法。如果你打开调试,你可以看到它传递给execute 的值,并确保它是实际的productID 值。
  • 另外,当您运行代码时,实际发生了什么?它是否会因为它是格式错误的查询而引发异常?返回错误的结果?以你的名义向奥巴马发送恐吓信?
  • @abarnert 我在 python 中没有异常。我只说它格式错误,因为如果我将它报告的查询全部转储到 mysql 工作台中,那么工作台会报告它格式错误。在 python 中,我得到一个从代码块末尾返回的 Query 对象。但是,该对象不包含数据库中的任何信息。
  • 好吧,你不能带参数的查询和不带参数的执行(这是mysql命令行工具、工作台等都会用它做的)。

标签: python mysql sql select sqlalchemy


【解决方案1】:

您需要执行查询,而不仅仅是返回它。查询一直是查询对象,直到在其上调用 all()first()scalar() 等方法或对其进行迭代。

你的方法应该是这样的:

@staticmethod
def getTrackableByProductId(productID, session):
    q = session.query(TrackableTable).filter_by(productID=productID)
    return q.first()

当您打印出查询时,SQLAlchemy 会使用格式占位符而不是实际值显示查询。实际查询是由 SQLAlchemy 控制之外的 dbapi(例如 python-mysql)构建的。


旁注:您的代码,无论是使用静态方法还是命名约定,看起来您都试图复制 Java 类。考虑阅读PEP8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多