2017-07-27 60 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

相关问题