1
我有下面的代碼,我運行一次,然後再次插入一個新的值來刷新。Python腳本返回舊的MySQL值(直到重新啓動)
def getStageAdditives(self, stage):
stagesAdditivesSelectQuery = """SELECT a.id,
a.name,
IFNULL(sa.dose, 0) as dose,
IFNULL(sa.last_dose, 0) as last
FROM additives a
LEFT JOIN stage_additives sa
ON a.id = sa.additive_id
AND sa.stage_id = (
SELECT id
FROM stages
WHERE name = '""" + stage + """')
ORDER BY a.name"""
self.cursor.execute(stagesAdditivesSelectQuery)
data = self.cursor.fetchall()
additives = []
for additive in data:
id = additive[0]
name = additive[1]
dose = additive[2]
last = additive[3]
additives.append({ 'title': name, 'dose': dose, 'last': last })
print stagesAdditivesSelectQuery
return additives
的問題是,當我使用下面的代碼中插入一個值「添加劑」表我老值(新值缺失)。
def createAdditive(self, name):
additiveInsertQuery = """ INSERT INTO additives
SET name = '""" + name + """'"""
try:
self.cursor.execute(additiveInsertQuery)
self.db.commit()
return "True"
except:
self.db.rollback()
return "False"
我可以通過查看phpMyAdmin來確認數值正在插入到數據庫中。如果我重新啓動腳本,我會按預期得到新值。如果我用phpMyAdmin運行查詢也返回新值。刷新頁面並等待10秒以上並沒有幫助,我仍舊得到舊值。
如果它很重要,兩種方法都在單獨的類/文件中。在'createAdditive'方法成功返回後,使用ajax調用getStageAdditives。
DB初始化:
import MySQLdb
import time
class Stage:
def __init__(self):
self.db = MySQLdb.connect('192.168.0.100', 'user', 'pass', 'dbname')
self.cursor = self.db.cursor()
檢索類似的值獲得新的值如預期(同一類createAdditives)的另一種方法:
def getAdditives(self, additive=None):
where = ''
if additive is not None:
where = "WHERE pa.additive_id = ("
where += "SELECT id FROM additives "
where += "WHERE name = '" + additive + "') "
where += "AND a.name = '" + additive + "'"
additiveSelectQuery = """ SELECT a.name,
pa.pump_id
FROM additives a,
pump_additives pa """ + where + """
ORDER BY a.name"""
self.cursor.execute(additiveSelectQuery)
data = self.cursor.fetchall()
additives = []
for item in data:
additives.append({'additive': item[0], 'pump': item[1]})
return additives
你使用'MYSQLdb'嗎?連接如何初始化? – alexis
請參閱編輯數據庫信息。 – DominicM
你如何確認'createAdditive'方法的結果?換句話說,你在代碼中檢查這個方法的結果? –