我用下面的代码连接mysql使用sqlalchemy,帮助我正确的代码。我的配置如下:
username: root
password: ''
host: localhost
port: 3307
db: logdb
mysql配置为:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/login'
代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/logdb'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
admin = User('root', 'admin')
db.create_all() # In case user table doesn't exists already. Else remove it.
db.session.add(admin)
db.session.commit() # This is needed to write the changes to database
User.query.all()
User.query.filter_by(username='root').first()
1条答案
按热度按时间yc0p9oo01#
你应该安装
pymysql
第一。然后将mysql配置为: