Flask flaskext.mysql no attribute connection

时间:2017-08-05 11:59:11

标签: python mysql flask

I'm trying to establish a connection to an sql database, but I end up with

AttributeError: 'MySQL' object has no attribute 'connection' 

I've read through the documentation, and it looks like this is the proper way to create a cursor:

from flask import Flask
from flaskext.mysql import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'sql3.freemysqlhosting.net'
app.config['MYSQL_USER'] = 'sql1234567'
app.config['MYSQL_PASSWORD'] = 'abcdefg'
app.config['MYSQL_DB'] = 'sql1234567'
app.config['MYSQL_PORT'] = '3306'
mysql = MySQL(app)

@app.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute('''SELECT * FROM users''')
    rv = cur.fetchall()
    return str(rv)

if __name__ == '__main__':
    app.run(debug=True)

Edit: using https://www.youtube.com/watch?v=nWO_VpI5wn8 as a tutorial and the docs are http://flask-mysqldb.readthedocs.io/en/latest/

2 个答案:

答案 0 :(得分:2)

您在此处导入错误的模块。

解决方案

而不是导入

from flask_mysqldb import MySQL

导入这是不同的模块(关注this

pip install flask-mysqldb

这看起来像某个IDE的自动导入问题。由于这两个模块不同,您可以按如下方式安装这两个软件包:

pip install flask-mysqlfrom flaskext.mysql import MySQL mysql = MySQL() mysql.init_app(app) cursor = mysql.get_db().cursor()

修改

如果您想使用上一个模块,则必须遵循this,光标可以如下使用:

{{1}}

答案 1 :(得分:-2)

尝试一下

安装python 3.6或旧版本

  • pip install flask-ext
  • 导入
  • 然后打开命令提示符>> mysql -u {host} -p >>输入密码>>“ abcdefg”(在您的情况下) 此密码应与本地主机用户密码(root)相同。
  • 如果登录,请创建数据库>>数据库名称为“ sql1234567”(以您为例)
  • 运行查询并提供您在代码中输入的相同列名

然后运行您的代码。它会连接它