Python-SQL对象通过字典和d选择数据

2024-09-28 03:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python2.7使用SQLObject,python的包装器来管理SQL查询。我知道我可以使用字典选择数据,例如:

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)

它不起作用。有没有办法按datetime范围和字典对过滤SQL查询?你知道吗


Tags: 数据sqldatetime字典tableselectyearday
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:24

解决了这个问题。如果你在这里面临同样的问题,以下是解决方法:

由于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)) + '"'

注意datetime对象周围的引号,即使它已被转换为字符串,它仍然需要有引号才能工作。你知道吗

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

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

相关问题 更多 >

    热门问题