如何使用SQLAlchemy连接到mysql

时间:2018-10-08 09:31:45

标签: python mysql sqlalchemy

我正在使用下面的代码使用SQLAlchemy连接mysql,请使用正确的代码帮助我。我的配置如下:

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 个答案:

答案 0 :(得分:0)

您应该先安装pymysql

pip install pymysql

,然后将您的mysql配置为:

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