每天学习一点MySQL系列(4)— 在select语句中使用变量

有时候需要在python环境下访问数据库,此时查询语句select中可能会使用不同的变量进行数据查询。

使用方法:

在select语句中用{}来代替变量,并且用.format(var1, var2, var3)


last_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() - 3600*24*1))
cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
#数据检索语句execute_str
execute_str = "select * from table_my where column1 like '%"+keywords_list[0]+"%' and column2 like '%"+hit_keyword+"%' and insert_time>'{}' and insert_time<'{}'".format(last_time, cur_time)
#建议使用以下比较统一的方式
execute_str = "select * from table_my where column1 like '%{}%' and column2 like '%{}%' and insert_time>'{}' and insert_time<'{}'".format(keywords_list[0],hit_keyword,last_time, cur_time)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章