flask 操做mysql的兩種方式-sqlalchemy操做

flask 操做mysql的兩種方式-sqlalchemy操做

2、ORM sqlalchemy操做

#coding=utf-8
# model.py

from app import db


class User(db.Model):

    user_id = db.Column(db.Integer, primary_key=True)
    user_name = db.Column(db.String)

    def __init__(self, user_id, user_name):
        self.user_id = user_id
        self.user_name = user_name



    def __str__(self):
        return "id:{id}-name:{name}".format(id = self.user_id, name = self.user_name)


#coding=utf-8
# app.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:root@123@localhost:3306/jikexueyuan"

db = SQLAlchemy(app)


@app.route("/")
def hello_world():
    return "hello world"


if __name__ == "__main__":
    app.run()



#coding=utf-8
# manage.py

from flask_script import Manager
from app import app, db
from model import User

manager = Manager(app)

@manager.command
def save():
    user = User(4, "curry")
    db.session.add(user)
    db.session.commit()


@manager.command
def query_all():
    users = User.query.all()
    for user in users:
        print user



if __name__ == "__main__":
    manager.run()




#表結構
CREATE DATABASE IF NOT EXISTS `jikexueyuan` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;


CREATE TABLE `jikexueyuan`.`user`(
        `user_id` INT NOT NULL,
        `user_name` VARCHAR(45) NULL,
        PRIMARY KEY (`user_id`))
ENGINE = INNODB;
相關文章
相關標籤/搜索