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/
答案 0 :(得分:2)
您在此处导入错误的模块。
解决方案
而不是导入
from flask_mysqldb import MySQL
导入这是不同的模块(关注this)
pip install flask-mysqldb
这看起来像某个IDE的自动导入问题。由于这两个模块不同,您可以按如下方式安装这两个软件包:
pip install flask-mysql
和
from 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
然后运行您的代码。它会连接它