【问题标题】:Inputting dates from python to a database从python输入日期到数据库
【发布时间】:2021-05-13 10:27:15
【问题描述】:

我有以下查询,我试图在 sql 查询中传递开始日期和结束日期。

def get_data(start_date,end_date):

    ic = Connector()
    q = f"""
    select * from example_table a 
    
    where a.date between {start_date} and {end_date}

    """
    result = ic.query(q)
    return result

df = pd.DataFrame(get_data('2021-01-01','2021-01-31'))
print(df)

这会导致以下错误:

AnalysisException: Incompatible return types 'STRING' and 'BIGINT' of exprs 'a.date' and '2021 - 1 - 1'.\n (110) (SQLExecDirectW)")

我也尝试如下解析日期:

 import datetime 
 start_date = datetime.date(2021,1,1)
 end_date = datetime.date(2021,5,13)
 df = pd.DataFrame(get_data(start_date,end_date))

但我仍然遇到同样的错误。 任何帮助将不胜感激。

【问题讨论】:

    标签: python sql date


    【解决方案1】:

    在我看来,这是因为您将值注入 sql 查询的方式不会被识别为日期值。数据库可能会将2021-01-01 解释为数学表达式,结果为2019

    您应该尝试在您的值周围加上括号。

        q = f"""
        select * from example_table a 
        where a.date between '{start_date}' and '{end_date}'
        """
    

    或者如果您的数据库库允许,最好不要直接注入您的值

        q = """
        select * from example_table a 
        where a.date between %s and %s
        """
        result = ic.query(q, (start_date, end_date))
    

    编辑:一些数据库可能使用与%s 不同格式的占位符。您可能应该查阅您正在使用的 db 库的文档。

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 2021-08-03
      • 2014-11-19
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 2019-01-20
      • 2018-12-06
      相关资源
      最近更新 更多