python写多行sql换行,并传递参数

方法一:

SQL太长,采用'''...'''的方式进行多行录入,占位符{0}、{1}...代替变量

然后在sql语句末尾,使用format()方法将参数传入占位符{0}、{1}...

注意:

{0}表示第一个占位符,{1}表示第二个占位符,

占位符位置有单引号的不可以省略,'{0}'。

此表达式不可以使用execute(sql_1,(day1,day2))传入参数

sql_1='''select count(value) from "D_COLLECT_MANUALDATA" 
    where collect_id like  'SP%' 
    and collect_time >= '{0}' ::TIMESTAMP and collect_time <= '{1}' ::TIMESTAMP; 
    '''.format(day1,day2)

cursor.execute(sql_1)

方法二:

使用双引号包裹SQL语句,在末尾用format()方法传入参数,

注意:使用\转义双引号",

sql_1="select count(value) from \"D_COLLECT_MANUALDATA\" where collect_id like  'SP%' and collect_time >= '{0}' ::TIMESTAMP and collect_time <= '{1}' ::TIMESTAMP;".format(day1,day2)

这个方法缺点是太长,可以使用()和" "的组合将多行字符串进行拼接,

PyCharm中,在字符串需要切割的位置回车,会自动加入拼接字符,

优化如下:

sql_1=("select count(value) from \"D_COLLECT_MANUALDATA\" "
       "where collect_id like  'SP%' "
       "and collect_time >= '{0}' ::TIMESTAMP and collect_time <= '{1}' ::TIMESTAMP;".format(day1,day2))

 

完整代码如下:

import psycopg2

conn = psycopg2.connect(
        host='119.3.5.255',
        port='5432',
        database='ay_test',
        user='aoyang',
        password='Aoyang123456',
    )
day1 = '2019-03-02 07:30:00'
day2 = '2019-03-03 07:30:00'
cursor =conn.cursor()


sql_1='''select count(value) from "D_COLLECT_MANUALDATA" 
    where collect_id like  'SP%' 
    and collect_time >= '{0}' ::TIMESTAMP and collect_time <= '{1}' ::TIMESTAMP; 
    '''.format(day1,day2)

cursor.execute(sql_1)
result2=cursor.fetchall() #返回的是一个tuple组成的list,格式[()]
print(result2)  #[(1726,)]
cursor.close()
conn.close()

 

你可能感兴趣的:(python写多行sql换行,并传递参数)