如何使用sqlalchemy连接到mysql

8xiog9wr  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(394)

我用下面的代码连接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()
yc0p9oo0

yc0p9oo01#

你应该安装 pymysql 第一。

pip install pymysql

然后将mysql配置为:

mysql+pymysql://root:password@127.0.0.1/logdb

相关问题