2017-07-27 37 views
0

我有一個Flask網站,其後端爲MySQL。我有一個叫做用戶的表格。它有兩列:用戶名和名稱,一個記錄:MySQLdb在與Flask Post一起使用時返回舊數據

name username 
Jim testuser123 

當用戶點擊網站上的按鈕,它更新記錄的名稱設置爲Bob然後打印所有記錄name = 'Bob'。但是,它不會返回任何結果。如果我在重新查詢之前刷新連接,那麼它確實會返回一個結果。 mdb.connect對象緩存數據嗎?它怎麼會不能返回正確的結果?

初始化的.py:

import pandas as pd 
import MySQLdb as mdb 
from flask import Flask, render_template, request 

def sql_con(): 
    return mdb.connect(host='myhost', port=3306, user='root', passwd='root', db='db', use_unicode=True, charset="utf8") 

app = Flask(__name__) 


def update_record(): 
    con = sql_con() 
    cur = con.cursor() 

    sql_string= "Update users set name = 'Bob' where username = 'testuser123'" 

    cur.execute(sql_string) 
    con.commit() 


@app.route('/', methods=['GET', 'POST']) 
def myroute(): 
    con = sql_con() 

    if request.method == 'POST': 
     update_record() 
     print pd.read_sql("select * from users where name = 'Bob'", con=con) 

    return render_template('1.html') 

app.run(debug=True, port=5050) 

1.HTML

<html> 

<body> 

    <form method="POST"> 
      <button id="mybutton" name='btn' value="mybutton">Submit Data</button> 
    </form> 
</body> 

對於這個代碼打印一個結果,我必須補充con=sql_con()我叫update()之後,但在print聲明之前。這是爲什麼?

+0

可能與https://stackoverflow.com/questions/29438471/how-to-prevent-pandas-psql-read-sql-query-from-fetching-cache相關 –

+0

可能重複[爲什麼選擇一些mysql連接舊數據mysql數據庫後刪除+插入?](https://stackoverflow.com/questions/9318347/why-are-some-mysql-connections-selecting-old-data-the-mysql-database-after-a -del) –

回答

1

通常,對於簡單的應用程序來說,即使ORM看起來過於簡單,對於Web框架使用ORM綁定(即Falsk-SQLAlchemy)也是一種很好的做法(管理連接池,自動執行提交/回滾,...)。

否則,如果您希望在低級別(數據庫連接)下管理此數據庫,請避免在同一請求中使用多個連接到同一數據庫。

試試這個:

import pandas as pd 
import MySQLdb as mdb 
from flask import Flask, render_template, request 

def sql_con(): 
    return mdb.connect(host='myhost', port=3306, user='root', passwd='root', db='db', use_unicode=True, charset="utf8") 

app = Flask(__name__) 


def update_record(con): 
    cur = con.cursor() 

    sql_string= "Update users set name = 'Bob' where username = 'testuser123'" 

    cur.execute(sql_string) 
    con.commit() 


@app.route('/', methods=['GET', 'POST']) 
def myroute(): 
    con = sql_con() 

    if request.method == 'POST': 
     update_record(con) 
     print pd.read_sql("select * from users where name = 'Bob'", con=con) 

    return render_template('1.html') 

app.run(debug=True, port=5050) 

如果你想基於這樣的解決方案來擴展一個真正的應用程序,你應該考慮拉從全球的連接池打開的連接。創建一個新的數據庫連接(在每個HTTP請求)可能會花費時間。

+0

謝謝,爲什麼使用綁定的好習慣? – user2242044

+0

我正在談論ORM綁定(對象關係映射器)來代替低級綁定,就像你的代碼一樣。谷歌「燒瓶sqlalchemy」得到的例子。這樣的ORM負責同步Web事務與數據庫事務,連接池管理,sql注入過濾,sql引用,對象<-> db行自動轉換,... – glenfant

相關問題