使用Flask,SQLAlchemy

时间:2018-01-04 08:04:44

标签: python mysql flask flask-sqlalchemy

我想使用Flask连接到 MySQL 数据库。以下是我的代码:

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'admin'
app.config['MYSQL_PASSWORD'] = '********'
app.config['MYSQL_DB'] = 'abc'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://admin:********@localhost/abc'

api = Api(app)
db = SQLAlchemy(app)
ma = Marshmallow(app)

db.create_all()

class Video(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    videoid = db.Column(db.String(80), unique=True)
    video_timestamp = db.Column(db.Integer, unique=True)

    def __init__(self, videoid, video_timestamp):
        self.videoid = videoid
        self.video_timestamp = video_timestamp

我遇到了这个错误:

  

sqlalchemy.exc.ProgrammingError:(pymysql.err.ProgrammingError)(1146,   "表' abc.video'不存在")[SQL:' SELECT video.id AS   video_id,video.videoid AS video_videoid,video.video_timestamp AS   video_video_timestamp \ nFROM video']

我知道如何连接 SQLite 数据库,但似乎很难连接到 MySQL 数据库?

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

连接到数据库没有问题,但看起来您的表尚未创建。 请删除代码中的db.create_all(),然后从the sql_alchemy official documentation

中查看
  

要创建初始数据库,只需从中导入db对象   交互式Python shell并运行SQLAlchemy.create_all()方法   创建表和数据库:

from yourapplication import db
db.create_all()

答案 1 :(得分:0)

连接到Mysql的代码:

from flaskext.mysql import MySQL

cursorclass,并自动提交以使生活更轻松

mysql = MySQL(autocommit=True, cursorclass= DictCursor)
app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!'
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = 8889
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql.init_app(app)

connect cursor 
cursor = conn.cursor()

您可以在phpmyadmin(localhost)

下载xxamp或Mamp并在线托管数据库