flask 操作mysql的两种方式-sql操作 一、用常规的sql语句操作 # coding=utf-8 # model.py import MySQLdb def get_conn(): conn = MySQLdb.connect("localhost", "root", "root@123", "jike") return conn class User(object): def __init__(self, user_id, user_name): self.user_id = user_id self.user_name = user_name def save(self): conn = get_conn() cursor = conn.cursor() sql = "insert into user (user_id, user_name) VALUES (%s, %s)" cursor.execute(sql, (self.user_id, self.user_name)) conn.commit() cursor.close() conn.close() @staticmethod def query_all(): conn = get_conn() cursor = conn.cursor() sql = "select * from user" cursor.execute(sql) rows = cursor.fetchall() users = [] for row in rows: user = User(row[0], row[1]) users.append(user) conn.commit() cursor.close() conn.close() return users def __str__(self): return "id:{id}-name:{name}".format(id = self.user_id, name = self.user_name) if __name__ == "__main__": user = User(1, "yaoming") user.save() #coding=utf-8 # app.py from flask import Flask app = Flask(__name__) @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 from model import User manager = Manager(app) @manager.command def save(): user = User(2, "jams") user.save() @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;