美文网首页
sqlalchemy的基本用法简单的sql语句执行

sqlalchemy的基本用法简单的sql语句执行

作者: 深夜程序员_ | 来源:发表于2020-04-13 18:34 被阅读0次

    from flask import Flask, jsonify, json

    from sqlalchemy import create_engine

    app = Flask(__name__)

    HOSTNAME = '127.0.0.1'

    PORT = '3306'

    DATABASE = 'pyDemo'

    USERNAME = 'root'

    PASSWORD = '123456'

    @app.route('/')

    def hello_world():

        # 连接数据库字符串

        DB_URI = "mysql://root:123456@127.0.0.1/pyDemo"

        engine = create_engine(DB_URI)

        # 判断是否连接成功

        engine.connect()

        # 删除一个表

        dropTable = engine.execute("drop table if EXISTS userDemo")

        # 创建一个表

        createTable = engine.execute("CREATE TABLE userDemo (id INT PRIMARY key AUTO_INCREMENT,NAME VARCHAR (255) NULL)")

        # 添加一条数据

        insertTable = engine.execute("insert into userDemo(name) value('test')")

        insertTable = engine.execute("insert into userDemo(name) value('test2')")

        # 查询一条数据

        selectUser = engine.execute("select * from userDemo")

        test = {}

        list = [];

        for userItem in selectUser:

            test = {'id': userItem[0], 'username': userItem[1]}

            list.append(test)

            print(userItem)

        return json.dumps(list)

    if __name__ == '__main__':

        app.run()

    相关文章

      网友评论

          本文标题:sqlalchemy的基本用法简单的sql语句执行

          本文链接:https://www.haomeiwen.com/subject/lcrpmhtx.html