将sql查询结果分配给Python

时间:2017-07-19 13:54:25

标签: python sql macros

我想将此查询的结果分配给变量,并将该变量用作另一个sql查询中的宏变量。

第一次查询:

start_week = 201619

start_date=connection.execute("""
select min(CAST(date_id as DATE)) as start_date from date_table
where CAST(week_id as INT) = %d
"""
%(start_week))

start_date = start_date.fetchone()

此查询的结果是:(datetime.datetime(2017,7,2,0,0),)

第二个查询:现在我想在第二个查询中使用它作为宏变量

start_wk=connection.execute("""
select fis_week_id as start_wk from date_dim
where date_id = %s
"""
%(start_date))

但是,我收到的错误如下:

DatabaseError: (cx_Oracle.DatabaseError) ORA-00936: missing expression
 [SQL: '\nselect week_id as start_wk from date_dim\nwhere date_id = (datetime.datetime(2016, 7, 4, 0, 0),)\n']

如果有人告诉我该怎么做,我会很感激吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

只需将日期时间字符串格式化为格式为'YYYY-M-D'的字符串,RDBMS将其读作日期时间。此外,将日期作为未在SQL字符串中插入的参数传递。请参阅Oracle+Python最佳做法:

str_start_date = datetime.datetime.strftime(start_date[0], '%Y-%m-%d')

cur = connection.cursor()

start_wk = cur.execute("""
   select fis_week_id as start_wk 
   from date_dim
   where date_id = to_date(:sdate, 'yyyy-mm-dd')""", {'sdate':str_start_date})

cur.close()

但是,考虑在不需要中间变量的情况下组合两个查询,其中第一个查询成为第二个查询的WHERE子句中的子查询:

cur = connection.cursor()

start_wk = cur.execute("""
   select fis_week_id as start_wk 
   from date_dim
   where date_id = (select min(CAST(date_id as DATE)) as start_date 
                    from date_table
                    where CAST(week_id as INT) = :sweek)""", {'sweek':start_week})
cur.close()