我目前正在學習如何使用 Python 和 MySQL,如果我的問題是基本問題,請見諒。我只是無法找到有關此問題的具體反饋。
關于下面的 insert() 函式,我喜歡我可以將操作和值分開。
def insert(item, price, category):
sql = "INSERT INTO Exp1 (item, price, category, date) VALUES (%s, %s, %s, %s)"
val = (item, price, category, datetime.now())
mycursor.execute(sql, val)
有沒有辦法對這個 get 類別函式做同樣的事情?就像我能夠將特定類別傳遞給函式一樣,將其存盤在 val 中并像以前一樣使用 sql 和 val 執行它?
# Get a given category from the database
def get_category():
sql = "SELECT * FROM Exp1 WHERE category = 'Groceries' ORDER BY date DESC"
mycursor.execute(sql)
for x in mycursor:
print(x)
uj5u.com熱心網友回復:
在MySQL的檔案顯示這個例子:
select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select_stmt, { 'emp_no': 2 })
擴展到您的情況,這樣的事情應該有效:
def get_category(category):
sql = "SELECT * FROM Exp1 WHERE category = %(category)s ORDER BY date DESC"
mycursor.execute(sql, {'category': category})
for x in mycursor:
print(x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/363540.html
