python在操作数据库执行sql的时候我们经常会遇到传参问题,以下是我总结的几种方法:
1、格式化字符串
city = ‘beijing‘cur.execute(“SELECT * FROM %s WHERE city = %s”, city)
2、使用字典传递
sql = “INSERT INTO user VALUES(%(username)s, %(password)s, %(email)s)”value = {“username”:zhangsan,“password”:123456,“email”:[email protected]}cur.execute(sql, value)
3、传递参数+参数名称:利用‘三引号’实现复杂SQL的换行,然后对参数进行拼接,如下样例中的time,根据自己的情况而定
def sql_func(time): time = "‘" + time + "‘" fail_sql=‘‘‘ SELECT substr(s_start_time,1,10) "日期",count(*) "失败数量" FROM T_SG_WS_EXE_LOG L WHERE 1 = 1 AND (S_WS_METHOD = ‘NotifyOrderStatus‘ OR (S_WS_METHOD = ‘placeOrder‘ AND S_IS_OK = ‘false‘)) and s_request_str not like ‘%"deployStatus":"2120"%‘ and s_request_str not like ‘%"deployStatus":"0"%‘ and substr(s_start_time,1,10) = ‘‘‘+time +‘‘‘group by substr(s_start_time,1,10) ‘‘‘ # 使用cursor进行各种操作 y=cr.execute(fail_sql) result = y.fetchall() return result 参考文档:https://www.cnblogs.com/goodhacker/p/3257882.html
原文地址:https://www.cnblogs.com/apff/p/10061835.html
时间: 2024-10-09 20:39:13