美文网首页
sequelize连接数据库,插入数据

sequelize连接数据库,插入数据

作者: Mokingc | 来源:发表于2019-12-16 23:29 被阅读0次

    安装sequelize

    npm install --save sequelize
    

    您还必须为所选数据库手动安装驱动程序:

    # One of the following:
    $ npm install --save pg pg-hstore # Postgres
    $ npm install --save mysql2
    $ npm install --save mariadb
    $ npm install --save sqlite3
    $ npm install --save tedious # Microsoft SQL Server
    

    建立连接:

    const sequelize = new Sequelize('blog', 'root', '123456', {
        host: 'localhost',
        dialect: 'mysql',
    });
    

    连接测试:

    sequelize
        .authenticate()
        .then(() => {
            console.log('Connection has been established successfully.');
        })
        .catch(err => {
            console.error('Unable to connect to the database:', err);
        });
    

    建立数据库模型:

    const Article = sequelize.define('article', {
        id: {
            type: Sequelize.BIGINT(11),
            primaryKey: true
        },
        title: {
            type: Sequelize.STRING
        },
        comment: {
            type: Sequelize.TEXT
        },
        content: {
            type: Sequelize.TEXT
        },
        tags: {
            type: Sequelize.STRING
        },
        catalogs: {
            type: Sequelize.STRING
        },
        date: {
            type: Sequelize.DATE
        }
    }, {
        freezeTableName: true,
        timestamps: false,
    });
    

    数据库查询

    router.get('/Article', async ctx => {
        ctx.body = await Article.findAll()
    })
    

    插入数据

    router.post('/issue', async ctx => {
        console.log("ctx.request.body", ctx.request.body)   
        console.log("ctx.request.files", ctx.request.files)     //文件
        console.log("ctx.request.fields", ctx.request.fields) //表单
        let { title, catalogs, tags, contents } = ctx.request.fields
        console.log(title, catalogs, tags, contents)
        Article.create({ title: title, catalogs: catalogs, tags: tags, content: contents })
    })
    

    删除数据

    router.post('/problem/catalog/delete/id', async ctx => {
        let { id } = ctx.request.fields
        Catalog.destroy({ where: { ID: id } })
        ctx.response = 'success'
    })
    

    相关文章

      网友评论

          本文标题:sequelize连接数据库,插入数据

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