使用带有元组的Pandas for IN语句时单击引号

时间:2017-08-18 18:20:37

标签: python postgresql pandas

我试图在psycopg2中使用IN语句。我传递了一个元组,但是我的一个项目是一个包含单引号的字符串(例如:l' Enfant Plaza)。

将其转换为元组时,Python会自动添加双引号(例如:' Union Station'," l' Enfant Plaza",' Dupont Cir&# 39))

因此,当我执行SQL查询时,我收到一个错误:

dataframe = pd.read_sql("""SELECT * FROM trips
                                WHERE originlocation IN {}
                            """.format(origin_locations_tuple), connection)


ERROR: column "l'Enfant Plaza" does not exist

1 个答案:

答案 0 :(得分:0)

Clodoaldo的建议让我走上正轨。使用pandas查询参数解决了它。工作版本如下所示:

sql = """SELECT * FROM final_trips_prod
                            WHERE (dateoftrip + origintime)
                                BETWEEN (TIMESTAMP %(datetime_selected)s - INTERVAL '3 HOURS')
                                AND (TIMESTAMP %(datetime_selected)s + INTERVAL '3 HOUR')
                            AND originlocation IN %(origin_locations)s
                            AND destinationlocation IN %(destination_locations)s
    """
dataframe = pd.read_sql_query(sql = sql,
                              con = connection,
                              params = {
                                  'datetime_selected': datetime_selected,
                                  'origin_locations': origin_locations,
                                  'destination_locations': destination_locations})