>  기사  >  웹 프론트엔드  >  Nodejs는 데이터베이스를 어떻게 운영합니까(추가, 삭제, 수정, 쿼리)?

Nodejs는 데이터베이스를 어떻게 운영합니까(추가, 삭제, 수정, 쿼리)?

青灯夜游
青灯夜游앞으로
2021-03-18 10:00:143302검색

이 글에서는 node에서 데이터베이스를 추가, 삭제, 수정, 확인하는 동작을 코드 예시를 통해 살펴보겠습니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다. ㅋㅋㅋ

nodejs 작업 데이터베이스 -Check -R
// 导包
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는 데이터베이스를 어떻게 운영합니까(추가, 삭제, 수정, 쿼리)?using 데이터베이스 신규 및 쿼리 인터페이스 인터페이스

// 导包
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();
직접 모듈을 작성하는 방법

// 导包
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();

by에 의해 작성된 모듈을 스스로 작성하는 모듈 mysql 모듈을 캡슐화

직접 작성한 mysql 모듈
// 导包
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();

자체 mysql 모듈 사용
// 导包
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("服务器开启成功...");
});

mysql-ithm 타사 라이브러리의 기본 사용
// 变量
// 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;

King of Glory 캡처 패킷 저장소

패킷 캡처

다음 타사 라이브러리가 사용됩니다

crewler

기능 소개:

Cheerio를 사용하여 서버측 DOM 및 자동 jQuery 삽입(기본값) 또는 JSDOM

구성 가능한 풀 크기 및 다시 실행

속도 제한 제어

요청에 대한 우선순위 대기열

Force 8 모드, 크롤러가 문자 집합 감지 및 변환 처리

4.x 이상과 호환 가능
  • // 导包
    const path = require("path");
    const myMoudle = require(path.join(__dirname, "01-我们自己写的模块.js"));
    // console.log(myMoudle);
    // myMoudle();
    console.log(myMoudle.baseUrl);
    myMoudle.insert();
    myMoudle.delete();
데이터베이스에

MySQL

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

module.exports = {
  // connection: connection
  // 简写
  connection,
};
을 운영하는 데 사용되는 다음 타사 라이브러리가 사용됩니다

  • 더 많은 프로그래밍 관련 지식을 보려면
  • 프로그래밍 소개
  • 를 방문하세요! !

위 내용은 Nodejs는 데이터베이스를 어떻게 운영합니까(추가, 삭제, 수정, 쿼리)?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제