『壹』 python 如何把變數的值傳遞給execute的sql中去
python 把變數的值傳遞給execute的sql中去的代碼:
import pymysql
db = pymysql.connect(host="119.XX.XX.XX",
port=3306,
user="XXXXXXXX",
passwd="XXXXXXXXXXXXX",
db="XXXXXX",
charset='utf8')
# %s 佔位符為需要傳遞的參數,切記不要加''雙引號,要不然會報錯
sql = "SELECT totalusercount * 1.4 FROM mm_project_uv_outdoor WHERE poiid = %s AND currenttime = %s"
cursor = db.cursor()
# 以下為傳遞多個參數的用法
cursor.execute(sql,['B00140N5CS','2019-04-23'])
# 傳遞單個參數時 cursor.execute(sql,'B00140N5CS')
print(cursor.fetchall())
db.close()
(1)pythonsql變數賦值擴展閱讀:
函數
Python的函數支持遞歸、默認參數值、可變參數,但不支持函數重載。為了增強代碼的可讀性,可以在函數後書寫「文檔字元串」(Documentation Strings,或者簡稱docstrings),用於解釋函數的作用、參數的類型與意義、返回值類型與取值范圍等。可以使用內置函數help()列印出函數的使用幫助。比如:
>>> def randint(a, b):
... "Return random integer in range [a, b], including both end points."...
>>> help(randint)
Help on function randint in mole __main__:
randint(a, b)
Return random integer inrange[a, b], including both end points.