【问题标题】:How to pass dataframe column of type dtype('<M8[ns]') as parameter to sql query of sql server database in pandas python?如何将 dtype('<M8[ns]') 类型的数据框列作为参数传递给 pandas python 中 sql server 数据库的 sql 查询?
【发布时间】:2020-09-02 14:26:39
【问题描述】:

我试过了:

 query =  "SELECT * FROM GPSEventsData09 where GPSDateTime Between '%s' and '%s'"
    
 data = pd.read_sql(query, con=engine, params = [new.iloc[0]['StartDateTime'],new.iloc[0]['EndDateTime']])

但我收到如下错误:

ProgrammingError: (pyodbc.ProgrammingError) ('SQL 包含 0 参数标记,但提供了 2 个参数', 'HY000') [SQL: SELECT * FROM GPSEventsData09 where GPSDateTime between '%s' and '%s'] [参数:(时间戳('2020-09-01 13:26:00'),时间戳('2020-09-01 14:26:00'))](此错误的背景: http://sqlalche.me/e/f405)vv

【问题讨论】:

    标签: python python-3.x pandas python-2.7 data-analysis


    【解决方案1】:

    您可以在 SQL 中执行此操作,但这不是您在 SQL 中执行参数的方式。我实际上建议您在 Python 中进行参数化,然后按原样使用生成的 SQL 字符串。更直接一点:

    query =  "SELECT * FROM GPSEventsData09 where GPSDateTime Between 'start_date' and 'end_date'"
    query = query.replace('start_date', new.iloc[0]['StartDateTime'].strftime('%m/%d/%Y %H:%M:%S'))
    query = query.replace('end_date', new.iloc[0]['EndDateTime'].strftime('%m/%d/%Y %H:%M:%S'))
    data = pd.read_sql(query, con=engine)
    

    【讨论】:

    • 我已经尝试过了,但它抛出了一个错误:TypeError Traceback (最近一次调用最后一次) in 1 query = "SELECT * FROM GPSEventsData09 where GPSDateTime Between start_date 和 end_date" ----> 2 query = query.replace('start_date', new.iloc[0]['StartTime']) 3 query = query.replace('end_date', new.iloc[0][ 'EndTime']) 4 data = pd.read_sql(query, con=engine) TypeError: replace() argument 2 must be str, not Timestamp
    • 然后您需要将 Pandas 时间戳转换为标准 SQL 类型的字符串 - 通常 mm/dd/yyyy 就足够了。试试new.iloc[0]['StartDateTime'].strftime('%m/%d/%Y')
    • 查看:TypeError Traceback(最近一次调用最后一次) in 4 new.iloc[0]['EndTime'] = new.iloc[0 ]['EndTime'].strftime('%m/%d/%Y') 5 ----> 6 query = query.replace('start_date', new.iloc[0]['StartTime']) 7 query = query.replace('end_date', new.iloc[0]['EndTime']) 8 data = pd.read_sql(query, con=engine) TypeError: replace() argument 2 must be str, not Timestamp跨度>
    • 但我也希望通过使用 strftime('%m/%d/%Y') 来显示日期时间,它只给出日期,我的格式是日期时间,并采用这个 ('%m/ %d/%Y %H:%M:%S') 抛出如下错误 ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]不正确'13' 附近的语法。(102) (SQLExecDirectW)") [SQL: SELECT Top 10 * FROM GPSEventsData09 where GPSDateTime Between 09/01/2020 13:26:00 and 09/01/2020 23:15:00]跨度>
    • SQL 语法可能需要在日期时间前后加上单引号。尝试编辑。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2019-01-02
    • 2012-02-23
    相关资源
    最近更新 更多