每天學習一點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)

 

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