3 回答

TA貢獻1871條經驗 獲得超8個贊
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()
擴展資料:
函數
Python的函數支持遞歸、默認參數值、可變參數,但不支持函數重載。為了增強代碼的可讀性,可以在函數后書寫“文檔字符串”(Documentation Strings,或者簡稱docstrings),用于解釋函數的作用、參數的類型與意義、返回值類型與取值范圍等??梢允褂脙戎煤瘮礹elp()打印出函數的使用幫助。比如:
>>> def randint(a, b):
... "Return random integer in range [a, b], including both end points."...
>>> help(randint)
Help on function randint in module __main__:
randint(a, b)
Return random integer inrange[a, b], including both end points.

TA貢獻1890條經驗 獲得超9個贊
問題:
curs.execute("select * from tables where userid=%s and code=%s")%(IDEntry2.get(),%IDEntry1.get()) #Entry獲取的值無法當成變量傳遞給execute的sql語句中。
問題是IDEntry1之前多了一個%
解決:
#curs.execute("select * from tables where userid=‘aaa’ and code=‘123’") //直接寫死就可以
按照可以的進行替換
selectSql = "select * from tables where userid=‘%s’ and code=‘%s’" % (str(IDEntry2.get()),str(IDEntry1.get()))#加str確認與%s匹配
curs.execute(selectSql)

TA貢獻1880條經驗 獲得超4個贊
添加回答
舉報