likes
comments
collection
share

Node连接MySql

作者站长头像
站长
· 阅读数 637

node连接数据库进行增删改查,安装npm包mysql2(npm install mysql2

1.创建连接池配置数据库信息

 const mysql = require('mysql2/promise');
 const pool = mysql.createPool({
     host: 'localhost',
     user: 'root',//数据库用户名
     database: 'blog',//数据库
     password: '',//数据库密码
     waitForConnections: true,//是否允许排队等待
     connectionLimit: 10,//最大连接数
     dateStrings: true //时间转字符串(转化格式)
 });
 module.exports = pool;

2.express创建路由

const express = require('express')
const app = express()
const router = express.Router()//创建路由
let pool = require('../../modules/pool')//引入配置好的数据库
router.get('/type', async(req, res) => {
//创建路由使用: http://localhost:端口号/type
//query中使用sql语句,rows是查询
        const [rows] = await pool.query(`select * from articletype ORDER BY time DESC;`);
        res.json({
//返回出去一段json
        })
})
module.exports = router;

3.挂载到主路由上面

app.use('/',require('./route/type/read-type'))
app.listen(3000, () => console.log(`博客接口运行`))

MySQL是目前最流行的数据库管理系统之一。在使用MySQL作为大型项目的数据库时我们经常需要编写很长很复杂的SQL语句,这里建议使用Sequelize作为操作数据库的ORM插件,这样我们在对于数据库操作的公共配置可以进行封装,并且可以以对象的形式操作SQL数据库官方文档