nodejs学习笔记 | node操作MySQL数据库

869 阅读2分钟

| 数据库软件安装

  1. MySQL Server:数据存储与服务
  2. MySQL Workbench: 可视化管理数据库

官网下载

dev.mysql.com/downloads/w…

image.png 傻瓜式安装,自行百度

| 操作步骤

  1. 安装操作数据库第三方模块
  2. 通过该模块连接MySQL数据库
  3. 通过mysql模块执行SQL语句

| 安装第三方模块mysql

nysql模块提供了在nodejs项目中连接和操作MySQL数据库的能力

  1. 安装
npm install mysql
  1. 配置
// 1.引入sql
const mysql = require('mysql');

// 2.建立连接
const db = mysql.createPool({
    host: '127.0.0.1', // 数据库地址
    user: 'root', // 数据库用户名
    password: '12345678', // 数据库密码
    database: 'demo_serve' // 库名
});

// 3.验证是否连接成功
db.query('SELECT 1', (err, result) => {
    // console.log(err, result);
    if (err) {
        console.log('数据库连接失败');
    } else {
        console.log('数据库连接成功');
    }
});

Q&A

Q1. 连接数据库时出现 Client does not support authentication protocol requested by server报错
A:
①通过命令行进入解压的mysql根目录下。
②登陆数据库

mysql -uroot -p

③输入root的密码

Enter password: ******

④更改加密方式(原样拷贝到命令窗中)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;

⑤更改密码:该例子中 123456为新密码

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';

⑥刷新:

mysql> FLUSH PRIVILEGES;

| 操作数据库

  1. 查询数据
db.query('select * from user_table', (err, result) => {
    console.log(result);
});
  1. 插入数据
const sqlStr = 'insert into user_table set ?';
let data = {
    username: '大伟',
    password: '9398460662',
};
db.query(sqlStr, data, (err, result) => {
    console.log(err?.message, result);
    res.send({
        CODE: '00',
        DATA: result,
    });
});
  1. 更新数据
app.get('/update/:id', (req, res) => {
    const { id } = req.params;

    const sqlStr = 'update user_table set ? where id=?';
    let data = {
        id: id,
        username: '深渊',
        password: '1304785565',
    };
    db.query(sqlStr, [data, data.id], (err, result) => {
        console.log(err?.message, result);
        if (!err) {
            res.send({
                CODE: '00',
                message: '更新成功',
            });
        } else {
            res.send({
                CODE: '002',
                message: '更新失败',
            });
        }
    });
});
  1. 删除数据
app.get('/delete/:id', (req, res) => {
    const { id } = req.params;

    const sqlStr = 'delete from user_table where id=?';
    db.query(sqlStr, id, (err, result) => {
        console.log(err?.message, result);
        if (result.affectedRows === 1) {
            res.send({
                CODE: '00',
                message: '删除成功',
            });
        } else {
            res.send({
                CODE: '002',
                message: '删除失败',
            });
        }
    });
});

注意:
使用delete语句会把数据真正删除,为了保险起见推荐使用标记删除,来模拟删除的动作,所谓的标记删除就是给每条信息添加一个status字段,来标记该条数据是否被删除

更新删除状态status

const id = 4
db.query('update user_table set status=1 where id=?', id, (err, result) => {
    if (err) {
        res.send({
            CODE: '002',
            message: '删除失败',
        });
    }
    if (result.affectedRows === 1) {
        res.send({
            CODE: '00',
            message: '删除成功',
        });
    }
});