Home  >  Article  >  Web Front-end  >  How does Nodejs operate the database (add, delete, modify, query)?

How does Nodejs operate the database (add, delete, modify, query)?

青灯夜游
青灯夜游forward
2021-03-18 10:00:143302browse

In this article, we will take a look at node through code examples on how to operate the database for additions, deletions, modifications and queries. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How does Nodejs operate the database (add, delete, modify, query)?

Related recommendations: "nodejs tutorial"

nodejs operation database-increased

// 导包
const express = require("express");
var mysql = require("mysql");

// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});

// 打开连接
connection.connect();

let name = "伟健";
let miaoshu = "哈哈哈很开心";
// 执行sql语句
connection.query(
  `insert into user(username,description) values("${name}","${miaoshu}")`,
  function (error, results) {
    if (error == null) {
      console.log(results); // 返回结果是一个对象
      console.log(results.affectedRows); // 受影响的行数,如果大于0,说明新增成功
      console.log(results.insertId); // 插入的这条数据的id
    }
  }
);

// 关闭连接
connection.end();

nodejs operation database-delete

// 导包
const express = require("express");
var mysql = require("mysql");

// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});

// 打开连接
connection.connect();

let id = 3;
let name = "千里jack";
let miaoshu = "新一代世界首富";
// 执行sql语句
connection.query(`delete from user where id = ${id}`, function (
  error,
  results
) {
  if (error == null) {
    console.log(results); // 返回结果是一个对象
    console.log(results.affectedRows); // 受影响的行数,如果大于0,说明新增成功
  }
});

// 关闭连接
connection.end();

nodejs operation database-change

// 导包
const express = require("express");
var mysql = require("mysql");

// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});

// 打开连接
connection.connect();

let id = 3;
let name = "千里jack";
let miaoshu = "新一代世界首富";
// 执行sql语句
connection.query(
  `update user set username="${name}",description="${miaoshu}" where id=${id}`,
  function (error, results) {
    if (error == null) {
      console.log(results); // 返回结果是一个对象
      console.log(results.affectedRows); // 受影响的行数,如果大于0,说明新增成功
    }
  }
);

// 关闭连接
connection.end();

nodejs operation database-check

// 导包
const express = require("express");
var mysql = require("mysql");

// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});

// 打开连接
// 其实这里这句代码可以不写,这个插件内部在你调用query执行sql语句的时候会自动的帮你打开连接
connection.connect();

// 执行sql语句
connection.query("select * from user", function (error, results, fields) {
  // 错误对象,如果没有错误就返回null
  // console.log(error);
  // 执行sql语句得到的结果集,有错的话就是undefined
  console.log(results);
  //   console.log(results[4].username);
  // 拿到的是字段的信息
  //   console.log(fields);
});

// 关闭连接
// 其实也可以不写,也是会自动关闭连接
connection.end();

Use database to add and query interface

// 导包
const express = require("express");
const multer = require("multer");
const bodyParser = require("body-parser");
const mysql = require("mysql");

// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});
// 创建一个uploads文件
var upload = multer({ dest: "uploads/" });

// 创建服务器
const app = express();

// 将uploads文件夹暴露出去,使得此文件夹内的文件可以直接被访问到
app.use(express.static("uploads"));

// 写路由
// 1. 写一个新增接口
// 参数:heroName,heroSkill,heroIcon(文件), 使用multer从前端接收
app.post("/hero/add", upload.single("heroIcon"), (req, res) => {
  let heroIcon = "http://127.0.0.1:4399/" + req.file.filename;
  let { heroName, heroSkill } = req.body;
  // 执行sql语句
  connection.query(
    `insert into hero(heroName,heroSkill,heroIcon) values("${heroName}","${heroSkill}","${heroIcon}")`,
    function (error, results) {
      if (error == null) {
        // 如果没有错则响应一个code为200的json对象
        res.send({
          code: 200,
          msg: "新增成功",
        });
      } else {
        res.send({
          code: 500,
          msg: "新增失败",
        });
      }
    }
  );
});

// 2. 写一个查询所有的英雄接口
// 参数:无
app.get("/hero/all", (req, res) => {
  // 直接读取数据库表中的所有的英雄,返回
  // 执行sql语句
  connection.query(
    `select id,heroName,heroSkill,heroIcon from hero where isDelete="false"`,
    function (error, results) {
      if (error == null) {
        // 如果没有错则响应一个code为200的json对象
        res.send({
          code: 200,
          msg: "查询成功",
          data: results,
        });
      } else {
        res.send({
          code: 500,
          msg: "服务器内部错误",
        });
      }
    }
  );
});

// 开启服务器
app.listen(4399, () => {
  console.log("服务器开启成功...");
});

How to write a module by yourself

We wrote it ourselves Module

// 变量
// let foodName = "红烧肉";
// // 把foodName暴露出去,为了使其可以被其他js文件导入
// module.exports = foodName;

// 函数
// function test() {
//   console.log("我是test函数");
// }
// module.exports = test;

// 对象
let db = {
  baseUrl: "http://127.0.0.1:4399",
  insert() {
    console.log("我是插入的方法");
  },
  delete() {
    console.log("我是删除的方法");
  },
};
module.exports = db;

Use the module we wrote ourselves

// 导包
const path = require("path");
const myMoudle = require(path.join(__dirname, "01-我们自己写的模块.js"));
// console.log(myMoudle);
// myMoudle();
console.log(myMoudle.baseUrl);
myMoudle.insert();
myMoudle.delete();

Encapsulate a mysql module by ourselves

A mysql module we wrote ourselves

const mysql = require("mysql");
// 创建一个和数据库的连接
var connection = mysql.createConnection({
  host: "localhost", // 数据库服务器的地址
  user: "root", // 账号
  password: "lijiazhao123", // 密码
  database: "maxiaoyu", // 数据库名
});

module.exports = {
  // connection: connection
  // 简写
  connection,
};

Using a mysql module we wrote ourselves

// 导包
const express = require("express");
const path = require("path");
// 导入我们自己写的mysql模块
const db = require(path.join(__dirname, "03-我们自己写一个mysql的模块.js"));

// 创建服务器
const app = express();

// 写一个查询所有英雄接口
app.get("/hero/all", (req, res) => {
  // 这里使用我们自己写的mysql模块,来操作数据库
  // 这里的db,就相当于是03那个文件里面暴露出来的对象
  // 这个对象里面又connection这个连接
  db.connection.query(
    `select id,heroName,heroSkill,heroIcon from hero where isDelete="false"`,
    (error, results) => {
      if (error == null) {
        res.send({
          code: 200,
          msg: "查询成功",
          data: results,
        });
      } else {
        res.send({
          code: 500,
          msg: "服务器内部错误",
        });
      }
    }
  );
});

// 开启服务器
app.listen(4399, () => {
  console.log("服务器开启了");
});

mysql-ithm Basic use of third-party libraries

//导入模块
const hm = require("mysql-ithm");

//2.连接数据库
//如果数据库存在则连接,不存在则会自动创建数据库
hm.connect({
  host: "localhost", //数据库地址
  port: "3306",
  user: "root", //用户名,没有可不填
  password: "lijiazhao123", //密码,没有可不填
  database: "hm", //数据库名称
});

//3.创建Model(表格模型:负责增删改查)
//如果table表格存在则连接,不存在则自动创建
let heroModel = hm.model("hero", {
  heroName: String,
  heroSkill: String,
});

// 4. 调用api
// 4.1 添加单个数据
// heroModel.insert(
//   { heroName: "波波", heroSkill: "骚的一批" },
//   (err, results) => {
//     console.log(err);
//     console.log(results);
//     if (!err) console.log("增加成功");
//   }
// );

// 4.2 批量添加数据
// let arr = [
//   {
//     heroName: "李白",
//     heroSkill: "一片诗意的酒,一曲长歌。一剑天涯,但愿长醉不复醒。",
//   },
//   {
//     heroName: "孙悟空",
//     heroSkill: "取经之路就在脚下,超脱三界之外,不在五行之中。",
//   },
//   { heroName: "貂蝉", heroSkill: "华丽又漂亮的生存到最后。" },
// ];
// heroModel.insert(arr, (err, results) => {
//   console.log(err);
//   console.log(results);
//   if (!err) console.log("增加成功");
// });

// 4.3 查询所有数据
// heroModel.find((err, results) => {
//   console.log(results);
// });

// 4.4 根据数据库字段查询部分数据
// ['name'] : 将要查询的字段放入数组中
// heroModel.find(["heroName", "heroSkill"], (err, results) => {
//   console.log(results);
// });

// 4.5 根据条件查询数据
// 'id=1' : 查询id为1的数据 (查询条件可以参考sql语句)
//例如 'age>10' : 查询age超过10的数据
//例如 'name>"张三"' : 查询名字为张三的数据,注意字符串添加引号
// heroModel.find("id>2", (err, results) => {
//   console.log(results);
// });

// 4.6 将数据库中 id = 1 的数据,age修改为30
// heroModel.update(
//   "id=2",
//   {
//     heroName: "千年之狐",
//     heroSkill: "青丘之灵的灵魂不会永远漂泊,因为我在这里",
//   },
//   (err, results) => {
//     console.log(results);
//   }
// );

//4.1 删除所有 id>3 的数据
// 这里删除是真正的把数据删掉
// 实际开发的时候不会用这个,因为开放的时候一般是软删除(使用更新)
heroModel.delete("id>3", (err, results) => {
  console.log(results);
});

King of Glory captures packets and stores them into the database

  • Captures packets

The following third-party libraries are used

crewler

Function introduction:

  • Server-side DOM and automatic jQuery insertion , using Cheerio (default) or JSDOM
  • Configurable pool size and redo
  • Control rate limit
  • Priority queue for requests
  • Force 8 Mode that lets the crawler handle character set detection and conversion
  • Compatible with 4.x or newer
// 1. 抓包:用爬虫crawler插件来爬网页上的数据

// 1. 抓包
// 导包
var Crawler = require("crawler");

// 创建一个爬虫实例
var c = new Crawler({
  maxConnections: 10,
  // This will be called for each crawled page
  callback: function (error, res, done) {
    if (error) {
      console.log(error);
    } else {
      var $ = res.$;
      // $ is Cheerio by default
      //a lean implementation of core jQuery designed specifically for the server
      //   console.log(JSON.parse(res.body)); // 所有的英雄,这是一个包含了很多对象的数组

      // 所有的英雄 都要去获取他的头像和技能
      // 所以要遍历出每一个英雄的ename,凭借一个详情页路径重新发请求
      JSON.parse(res.body).forEach((v) => {
        // console.log(`https://pvp.qq.com/web201605/herodetail/${v.ename}.shtml`);
        // Queue just one URL, with default callback
        xq.queue(`https://pvp.qq.com/web201605/herodetail/${v.ename}.shtml`);
      });
    }
    done();
  },
});

// 声明一个全局遍历heros数组,用来存放所有的英雄的
let heros = [];

// Queue just one URL, with default callback
c.queue("https://pvp.qq.com/web201605/js/herolist.json");

// 创建一个请求详情的爬虫实例
var xq = new Crawler({
  maxConnections: 10,
  // This will be called for each crawled page
  callback: function (error, res, done) {
    if (error) {
      console.log(error);
    } else {
      var $ = res.$;
      // $ is Cheerio by default
      //a lean implementation of core jQuery designed specifically for the server
      // 英雄名字 英雄技能 英雄头像
      // console.log($(".cover-name").text(), $(".skill-name>b").first().text());
      // console.log("https:" + $(".ico-play").prev("img").attr("src"));

      // 把获取到的英雄名字 英雄技能 英雄头像都添加到这个数组中
      heros.push({
        heroName: $(".cover-name").text(),
        heroSkill: $(".skill-name>b").first().text(),
        heroIcon: "https:" + $(".ico-play").prev("img").attr("src"),
        isDelete: false,
      });
    }
    done();
  },
});

// 要等待所有的请求全部做完之后,才入库
xq.on("drain", function () {
  // For example, release a connection to database.
  // 调用API:添加数据
  heroModel.insert(heros, (err, results) => {
    console.log(err);
    console.log(results);
    if (!err) console.log("增加成功");
  });
});
  • Inbound

#The following third-party libraries are used

is used to operate MySQL

// 2. 入库:用mysql-ithm插件把爬到的数据装进数据库中
//1.导入模块
const hm = require("mysql-ithm");

//2.连接数据库
//如果数据库存在则连接,不存在则会自动创建数据库
hm.connect({
  host: "localhost", //数据库地址
  port: "3306",
  user: "root", //用户名,没有可不填
  password: "lijiazhao123", //密码,没有可不填
  database: "wzry", //数据库名称
});

//3.创建Model(表格模型:负责增删改查)
//如果table表格存在则连接,不存在则自动创建
let heroModel = hm.model("hero", {
  heroName: String,
  heroSkill: String,
  heroIcon: String,
  isDelete: String,
});
For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of How does Nodejs operate the database (add, delete, modify, query)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete