nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

青灯夜游
풀어 주다: 2021-09-22 10:09:26
앞으로
5346명이 탐색했습니다.

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법은 무엇입니까? 다음 기사에서는 node.js를 기반으로 데이터베이스에 데이터 추가 및 쿼리 기능을 구현하는 방법을 보여 드리겠습니다.

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

node.js를 기반으로 데이터베이스 추가 및 쿼리 구현

Ideas

  • 프로젝트 서버 API 생성

  • 프로젝트 폴더 초기화

rr ​​reee
  • 설치 패키지
npm init --y
로그인 후 복사
로그인 후 복사
  • restfulf style

  • Postman 소프트웨어를 사용하여 테스트

[권장 학습: "nodejs tutorial"]

프로젝트 구조 차트

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

업적

< code>sql.js파일 코드는 다음과 같습니다.sql.js文件代码如下:

npm i express mysql
로그인 후 복사
로그인 후 복사

server.js文件 参考代码

// 1. 加载msyql
var mysql = require(&#39;mysql&#39;);

// 2. 创建连接
var connection = mysql.createConnection({
  host     : &#39;localhost&#39;,   // 你要连接的数据库服务器的地址
  port     : 3306,// 端口号
  user     : &#39;root&#39;,        // 连接数据库服务器需要的用户名
  password : &#39;root&#39;,        // 连接数据库服务器需要的密码
  database : &#39;yanyan&#39;      //你要连接的数据库的名字
});

// 3. 连接数据库
connection.connect((err) => {
  // 如果有错误对象,表示连接失败
  if (err) return console.log(&#39;数据库连接失败&#39;)
  // 没有错误对象提示连接成功
  console.log(&#39;mysql数据库连接成功&#39;)
});

module.exports = connection
로그인 후 복사

运行结果

  • sql数据库

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

  • postman测试

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

  • 控制台输出结果

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

使用路由中间件优化方案

思路

  • 创建项目

  • 初始化项目文件夹

const express = require("express");
const app = express();
const connection = require("./utils/sql");

app.use(express.urlencoded());
// 添加数据接口
app.post("/api/student", (req, res) => {
  console.log(req.body);
  // 接收普通键值对参数
  const { name, sex, age } = req.body;
  // 添加到数据库中
  const sql = `insert into Students(name,sex,age) value(&#39;${name}&#39;,&#39;${sex}&#39;,${age})`;
  //console.log("要执行的sql", sql);
  // result 接受的数据
  connection.query(sql, (err, result) => {
    if (err) {
      console.log(err);
      res.json({ msg: "添加失败", code: 0 });
    } else {
      console.log(result);
      res.json({ msg: "添加成功", code: 1 });
    }
  });
});

// 获取数据接口
app.get("/api/student", (req, res) => {
  const sql = `select * from Students `;
  connection.query(sql, (err, result) => {
    if (err) {
      console.log(err);
      res.json({ msg: "获取失败", code: 0 });
    } else {
      console.log(result);
      res.json({ msg: "获取成功", code: 0, data: result });
    }
  });
});

app.listen(3000, () => {
  console.log("接口服务器启动,端口号为3000");
});
로그인 후 복사
  • 安装包
npm init --y
로그인 후 복사
로그인 후 복사
  • restfulf 风格

  • 使用Postman软件测试

项目结构图

nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법

实现

sql.js文件

npm i express mysql
로그인 후 복사
로그인 후 복사

get.js文件

// 1. 加载mysql
var mysql = require("./node_modules/mysql");
// 2. 创建连接
var connection = mysql.createConnection({
  host: "localhost", // 你要连接的数据库服务器的地址
  port: 3306, // 端口号
  user: "root", // 连接数据库服务器需要的用户名
  password: "root", // 连接数据库服务器需要的密码
  database: "yanyan", //你要连接的数据库的名字
});
// 3. 连接数据库
connection.connect((err) => {
  // 如果有错误对象,表示连接失败
  if (err) return console.log("数据库连接失败");
  // 没有错误对象提示连接成功
  console.log("mysql数据库连接成功");
});

module.exports = connection;
로그인 후 복사

post.js文件

const connection = require("./sql");
const express = require("./node_modules/express");
const router = express.Router();

router.use(express.urlencoded());
//获取数据接口
router.get("/api/student", (req, res) => {
  const sql = `select * from Students`;
  connection.query(sql, (err, result) => {
    if (err) {
      console.log(err);
      res.json({ msg: "获取失败", code: 0 });
    } else {
      console.log(result);
      res.json({ msg: "获取成功", code: 0, data: result });
    }
  });
});

module.exports = router;
로그인 후 복사

server-pro.js

const connection = require("./sql");
const express = require("./node_modules/express");
const router = express.Router();
router.use(express.urlencoded());
// 添加数据接口
router.post("/api/student", (req, res) => {
  //console.log(req.body);
  // 接收普通键值对参数
  const { name, sex, age } = req.body;
  // 添加到数据库中
  const sql = `insert into Students(name,sex,age) values(&#39;${name}&#39;,&#39;${sex}&#39;,${age})`;
  //console.log("要执行的sql", sql);
  // result 接受的数据
  connection.query(sql, (err, data) => {
    if (err) {
      console.log(err);
      res.json({ msg: "添加失败", code: 0 });
    } else {
      console.log(data);
      res.json({ msg: "添加成功", code: 1 });
    }
  });
});

module.exports = router;
로그인 후 복사

server.js파일 참조 코드


const get = require("./utils/get");
const post = require("./utils/post");
const express = require("./node_modules/express");
const app = express();

app.use("/utils/get", get);
app.use("/utils/post", post);

app.listen(3000, () => {
  console.log("接口服务器启动,端口号为3000");
});
로그인 후 복사

실행 결과

sql 데이터베이스

🎜nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법🎜🎜🎜우체부 테스트🎜🎜🎜nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법🎜🎜🎜콘솔 출력 결과🎜🎜🎜nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법 🎜🎜🎜라우팅 미들웨어 최적화 솔루션 사용🎜🎜🎜🎜🎜Ideas🎜🎜🎜🎜🎜🎜프로젝트 생성🎜🎜🎜🎜프로젝트 폴더 초기화🎜🎜🎜rrreee🎜🎜패키지 설치 🎜🎜rrreee 🎜🎜🎜편안한 스타일 🎜🎜🎜 🎜Postman 소프트웨어를 사용하여 테스트🎜🎜🎜🎜🎜프로젝트 구조 다이어그램🎜🎜🎜nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법🎜🎜🎜🎜implementation🎜🎜🎜🎜🎜 sql.js파일🎜🎜rrreee🎜🎜<code>get.js파일🎜🎜rrreee🎜🎜post.js파일🎜🎜rrreee🎜🎜서버- pro.js파일🎜🎜rrreee🎜🎜원본 주소: https://juejin.cn/post/7008779311666692126🎜🎜🎜저자: Buco🎜🎜🎜프로그래밍 관련 지식을 더 보려면 다음을 방문하세요: 🎜프로그래밍 비디오🎜 ! ! 🎜

위 내용은 nodejs에서 데이터베이스 데이터를 추가하고 쿼리하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!