【问题标题】:Python SQL Object selecting data by dictionary and datePython SQL对象按字典和日期选择数据
【发布时间】:2016-08-19 17:47:57
【问题描述】:

我在 Python 2.7 中使用 SQLObject,一个用于管理 SQL 查询的 Python 包装器。我知道我可以使用字典来选择数据,例如:

restrictions = { ... }
selection = sql_table.selectBy(**restrictions).orderBy('-createdtime')

我也可以通过以下方式查询日期:

selection = sql_table.select(sql_table.q.creatdtime>=datetime.datetime(year, month, day, 0, 0, 0, 0)

但是,我想同时使用两者来按日期和字典配对排序。当我尝试像这样将它们放在一起时:

selection = sql_table.select(**restrictions, sql_table.q.creatdtime>=datetime.datetime(year, month, day, 0, 0, 0, 0)

它不起作用。有什么方法可以按日期时间范围和字典配对过滤 SQL 查询?

【问题讨论】:

    标签: python mysql python-2.7 dictionary sqlobject


    【解决方案1】:

    解决了这个问题。如果您在这里遇到同样的问题,这里是解决方案:

    由于 Python 的 SQLObject 包装器支持直接输入 SQL 查询,因此我选择自己构建它。首先,我将所有限制解压缩为一个查询

    select_string = " AND ".join(str(key) + "=" + str(restrictions[key]) for key in restrictions.keys())
    

    然后我想根据我的日期添加限制。我知道我的数据库中存储日期和时间的列叫做createdtime,所以我把字符串写成

    select_string += " AND " + 'createdtime>=' + '"' + str(datetime.datetime(year, month, day, 0, 0, 0, 0)) + '"'
    

    注意日期时间对象周围的引号,即使它已被转换为字符串,它仍然需要有引号才能工作。

    因此,我的最终代码如下所示:

    select_string = " AND ".join(str(key) + "=" + str(restrictions[key]) for key in restrictions.keys())
    if date1:
        select_string += " AND " + 'createdtime>=' + '"' + str(datetime.datetime(year, month, day, 0, 0, 0, 0)) + '"'
    if date2:
        select_string += " AND " + 'createdtime<=' + '"' + str(datetime.datetime(year2, month2, day2, 0, 0, 0, 0)) + '"'
    selection = sql_table.select(select_string).orderBy('-createdtime')
    return selection
    

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多