用于psycopg2连接的python中长查询的SQL格式化示例

时间:2016-04-22 21:44:43

标签: python sql postgresql psycopg2

通常我会使用Pandas来查看和播放数据,这是我熟悉的。

如果我使用psycopg2模块从postgres数据库中提取数据,我将SQL查询放在python文件中,但如果它是一个复杂的查询,它会在一条线上延伸到远离屏幕。

有没有办法在python中使用换行符获取SQL查询?即某种使python忽略空格的特殊字符包装器?

sql = SELECT devices.id, devices.names, devices.addresses, devices.charging, devices.covered, record_temperatures.time
FROM devices
WHERE devices.imei like '%0444258';

df = pd.read_sql_query(sql, con=conn) 

不是这个

sql = SELECT devices.id, devices.names, devices.addresses, devices.charging, devices.covered, record_temperatures.time FROM devices WHERE devices.imei like '%0444258';

df = pd.read_sql_query(sql, con=conn) 

1 个答案:

答案 0 :(得分:4)

您可以使用反斜杠:

sql = "SELECT devices.id, devices.names, devices.addresses,\
devices.charging, devices.covered, record_temperatures.time \
FROM devices \
WHERE devices.imei like '%0444258'";

或者您也可以使用三重报价:

sql = """SELECT devices.id, devices.names, devices.addresses,  
devices.charging, devices.covered, record_temperatures.time
FROM devices
WHERE devices.imei like '%0444258';
"""