Flask-mysqldb数据库游标

时间:2017-06-19 12:18:50

标签: python mysql flask flask-mysql

我使用Flask配置了Python Web服务器,使用flask-mysqldb配置了数据库。 目前,我在应用程序的开头有数据库连接,如下所示:

from flask_mysqldb import MySQL

app = Flask(__name__)
mysql = MySQL(app)

每条路线都有这样的光标:

@app.route('/action')
def execute_action():
    cursor = mysql.connection.cursor()
    # processing
    cursor.connection.close()
@app.route('/load')
def load_data():
    cursor = mysql.connection.cursor()
    # processing
    cursor.connection.close()

但是,现在我需要从其他类和函数中访问相同的数据库连接,但是将连接作为参数传递不是一个选项。反正我是否可以声明全局并从其他类访问它? “app”或“mysql”。或者更好的方法呢?

道歉,如果它太基础,我使用Python和Flask相对较新

1 个答案:

答案 0 :(得分:0)

已经的连接是全局的。无论您从何处访问mysql.connection,都可以next()访问同一请求中的select t1.id, t3.name_1, t2.info_1, t3.name_2 from table1 t1, table2 t2, table3 t3 where t1.info_1 = t2.info_1 and t1.name_1 = t3.name_1