sequelize连接数据库,插入数据

安装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'
})
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容