search
HomeWeb Front-endJS TutorialHow to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

This article will introduce to you how to use Nodejs to connect to Mysql and implement basic CRUD operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

[Recommended study: "nodejs Tutorial"]

The main technical points of the following sample code Includes

  • Basic framework

    • Koa

    • Koa-router

    • koa-nunjucks-2

  • ##Mysql connection package

    • mysqljs

0. Prerequisites

  • Install mysql database And start

  • Install Nodejs (there should be no problems with this)

1. Node connects to the database

  • Create an empty folder

  • Execute

    yarn add koa koa-router mysql

  • Create a js (test.js) file in the root directory to test the database connection operation

  • Let’s first write a paragraph in test.js Code, output hello, ensure that the startup program does not report an error

    const Koa = require("koa") // 导入koa
    const Router = require("koa-router") //导入koa-router
    const mysql = require("mysql")  // 导入mysql,连接mysql 需要用到
    const app = new Koa(); // 实例化koa
    const router = new Router(); // 实例化路由
    // 创建一个路径为/hello的get请求
    router.get("/hello", async ctx => {
    // 返回 字符串 hello
        ctx.body = "hello"
    
    })
    
    // koa注册路由相关
    app
    .use(router.routes())
    .use(router.allowedMethods())
    // 监听端口
    .listen(3333,()=>{
        console.log("server running port:" + 3333);
    })

    • Execute

      node test.js or nodemon test.js in the project root directory Starting the project

    • Using

      nodemonStarting the project requires global installationyarn global add nodemon ornpm i -g nodemon

    • Use

      nodemon to start the project, nodemon will monitor the files in the startup directory, if any files change, nodemon The node application will be automatically restarted. It is strongly recommended to use nodemon to start the node project

    • After the project is started, we enter

      http:// in the browser localhost:3333/hello, you can see the text hello output on the page
      How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

    • After this interface appears, it proves that there is no problem with the startup of our project

    • Next we will use node to connect to the mysql database

  • Let’s prepare a wave of data first

          CREATE DATABASE db1;
          USE db1;
          CREATE TABLE user (
        	id INT PRIMARY KEY auto_increment,
          	NAME VARCHAR(20) NOT NULL,
         	age INT NOT NULL
          ); 
          INSERT INTO user VALUES 
          (null, "张三", 23),
          (null, "李四", 24),
          (null, "王五", 25),
          (null, "赵六", 26);

2. Connect to the mysql database to implement the table display function

  • Next we will test.js Write the code to connect to mysql

      const Koa = require("koa") // 导入koa
      const Router = require("koa-router") //导入koa-router
      const mysql = require("mysql")  // 导入mysql,连接mysql 需要用到
      const app = new Koa(); // 实例化koa
      const router = new Router(); -- 实例化路由
    
      // mysqljs 连接 mysql数据库
      let connection = mysql.createConnection({
          host: '127.0.0.1', // mysql所在的主机,本地的话就是 127.0.0.1 或者 localhost, 如果数据库在服务器上,就写服务器的ip
          user: 'root', // mysql的用户名
          password: '密码', // mysql的密码
          database: 'db1' // 你要连接那个数据库
      })
    
      // 连接 mysql
      connection.connect(err=>{
          // err代表失败
          if(err) {
              console.log("数据库初始化失败");
          }else {
              console.log("数据库初始化成功");
          }
      })
    
      // 创建一个路径为/hello的get请求
      router.get("/hello", async ctx => {
      // 返回 字符串 hello
          ctx.body = "hello"
    
      })
    
      // koa注册路由相关
      app
      .use(router.routes())
      .use(router.allowedMethods())
      // 监听端口
      .listen(3333,()=>{
          console.log("server running port:" + 3333);
      })

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

    • ## Terminal output
    • Database initialization successful

      text means that the database connection is successful

    • Just now we have prepared four pieces of data in the db1 database, and then we can put the data The query is displayed and displayed on the console
  • We add this query code under the connection.connect method
    • The first parameter of the connection.query method is a
    • sql

      statement of string type. The second parameter is optional. As will be mentioned later, the last parameter is a parameter that contains error information and correct response result data. Method<pre class="brush:php;toolbar:false">  const selectSql = &quot;SELECT * FROM user&quot;   connection.query(selectSql, (err,res) =&gt; {       if(err) console.log(err);       console.log(res);   })</pre>

  • The data returned is like this
  • How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

      At this time, the data in the database has been queried, then we can return the data to the front end in JSON format
  • By adding this paragraph The code returns the data to the browser in JSON format
  •   // 因为 mysqljs不支持 Promise方式CRUD数据
      // 所以我们做一个简单的封装
      function resDb(sql) {
          return new Promise((resolve,reject) => {
              connection.query(sql, (err,res) => {
                  if(err) {
                      reject(err)
                  }else {
                      resolve(res)
                  }
              })
          })
      }
    
      //请求 /userAll 的时候返回数据
      router.get("/userAll", async ctx => {
          ctx.body =  await resDb("SELECT * FROM user")
      })

    How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

      This data is what we need, uh uh uh, the data is returned , we are doing the front-end, how can we not have a page? First add a table page to display data. The
    • nunjucks

      template engine is used here. Let’s install it firstyarn add koa-nunjucks-2

  • Add this code to test.js
  •   const koaNunjucks = require(&#39;koa-nunjucks-2&#39;);
      const path = require(&#39;path&#39;);
    
       // 注入 nunjucks 模板引擎
       app.use(koaNunjucks({
          ext: &#39;html&#39;, // html文件的后缀名
          path: path.join(__dirname, &#39;views&#39;), // 视图文件放在哪个文件夹下
          nunjucksConfig: {
            trimBlocks: true // 自动去除 block/tag 后面的换行符
          }
        }));
        //在 /userAll这个路由中我们不直接返回数据了,我们返回table.html页面
      router.get("/userAll", async ctx => {
      const userAll = await resDb("SELECT * FROM user")
      await ctx.render("table",{userAll})
      })
    By nunjucks Template engine, we put all html files in the views folder in the root directory, then we need to create a views folder in the root directory, and create the table.html file in the folder. The file code is as follows
  •     <!DOCTYPE html>
          <html>
          <head>
              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Document</title>
              <style>
                  .table{
                      width: 500px;
                  }
                  td{
                      text-align: center;
                  }
              </style>
          </head>
          <body>
              <table border="1"  cellspacing="0">
                  <thead>
                      <tr>
                          <th>id</th>
                          <th>姓名</th>
                          <th>年龄</th>
                      </tr>
                  </thead>
                  <tbody>
                      {% for user in userAll %}
                      <tr >
                          <td>{{user.id}}</td>
                          <td>{{user.NAME}}</td>
                          <td>{{user.age}}</td>
                      </tr>
                      {% endfor %}
                  </tbody>
              </table>
          </body>
          </html>

  • After restarting the server, visit
  • http://localhost:3333/userAll

    How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations##this page After it comes out, the display part is done

    The query function is completed, and then we can implement the new functions

3、 添加数据到mysql数据库中

  • 我们先把table.html页面的添加部分写完

      <form action="/addUser">
          <label for="name">
              用户名:
              <input type="text" name="name" placeholder="请输入用户名">
          </label>
          <label for="age">
              年龄:
              <input type="number" name="age" min="0" placeholder="请输入年龄">
          </label>
          <input type="submit" value="添加">
      </form>
  • 这个时候页面是长这样的

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

  • 当我们输入完用户名和年龄点击添加按钮后,浏览器会通过 get请求 把数据发送到 /addUser 这个路由中,接下来,我们在test.js中接收一下前端传的参数,并且把参数保存到数据库中。然后刷新页面

    //请求 /addUser 接受前端传过来的数据,并且把数据持久化到数据库中
      router.get("/addUser", async ctx => {
          const { name, age } = ctx.query
          // 判断 name 和 age是否有值,都有值时,数据存入数据库,刷新表格页面
          // 否则直接返回到表格页面
          if(name && age) {
          await resDb("INSERT INTO user values(null,?,?)",[name, age])
          }
           //重定向路由,到 userAll
          ctx.redirect("/userAll")
      })
  • 为了提高 resDb 的健壮性,我们对这个方法进行了升级

      function resDb(sql, params) {
          return new Promise((resolve,reject) => {
              let sqlParamsList = [sql]
              if(params) {
                  sqlParamsList.push(params)
              }
              connection.query(...sqlParamsList, (err,res) => {
                  if(err) {
                      reject(err)
                  }else {
                      resolve(res)
                  }
              })
          })
      }
  • 升级之后的这个方法适合 CRUD的 promise 化了,当然 修改和删除功能下边我们会说

  • 到这个时候,我们的新增功能就完成了,那么我们来看一波截图,并且理一下逻辑

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

4、 通过id更新数据

  • 更新数据的前端部分,我们就不写模态框了,直接写个类似新增的表单,实现更新的操作吧,其实新增和更新功能非常类似,有差别的地方只是sql的写法

  • 我们先把table.html页面改造一下

          <form action="/updateUser">
              <label for="id">
                  id:
                  <input type="number" name="id" placeholder="请输入要更新的ID">
              </label>
              <label for="name">
                  用户名:
                  <input type="text" name="name" placeholder="请输入用户名">
              </label>
              <label for="age">
                  年龄:
                  <input type="number" name="age" min="0" placeholder="请输入年龄">
              </label>
              <input type="submit" value="修改">
          </form>
  • 下面我们看下后台的代码

      //请求 /updateUser 接受前端传过来的数据,并且把数据持久化到数据库中
      router.get("/updateUser", async ctx => {
          const { id, name, age } = ctx.query
          // 判断 id, name 和 age是否有值,都有值时,更新数据库中的数据,刷新表格页面
          // 否则直接返回到表格页面
          if(id, name && age) {
          await resDb("UPDATE user SET name=?, age=? WHERE id=?",[name, age, id])
          }
          //重定向路由,到 userAll
          ctx.redirect("/userAll")
      })
  • 代码逻辑和新增部分的逻辑是一样的,

  • 刚才在写新增和更新的sql代码,大家会看到sql语句中有?占位符,第二个参数数组是?占位符对应的内容。那么这个时候大家肯定会有这样一个疑问,为啥我们不直接把前端传过来的参数拼进去。非得这么麻烦。

  • 其实这样通过占位符的方式写sql是为了防止 sql注入,有关sql注入的文章大家可以参考这篇 sql注入原理及防范

5、通过id删除单条数据

  • 老规矩我们先把table.html页面改造一下

      <table class="table" border="1"  cellspacing="0">
          <thead>
              <tr>
                  <th>id</th>
                  <th>姓名</th>
                  <th>年龄</th>
                  <th>操作</th>
              </tr>
          </thead>
          <tbody>
              {% for user in userAll %}
              <tr >
                  <td>{{user.id}}</td>
                  <td>{{user.NAME}}</td>
                  <td>{{user.age}}</td>
                  <td>
                      <a href={{&#39;/delete/&#39;+user.id}}>删除</a>
                  </td>
              </tr>
              {% endfor %}
          </tbody>
      </table>
  • 看下页面效果

    How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

  • 老规矩,下面我们来看看后台的代码

      //请求/delete/:id  接受前端传过来的数据,并且把对应的id的数据删掉
      router.get("/delete/:id", async ctx => {
          const { id } = ctx.params
          // 判断 id否有值,有值时,根据id删除数据库中的数据,刷新表格页面
          // 否则直接返回到表格页面
          if(id) {
          await resDb("DELETE FROM user WHERE id=?",[id])
          }
          //重定向路由,到 userAll
          ctx.redirect("/userAll")
      })
  • 到目前为止对表格的增删改查(CRUD),就都已经写完了。

6、 完整代码

  • 目录结构

    1How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations

  • package.json

        {
           "koa": "^2.13.1",
           "koa-nunjucks-2": "^3.0.2",
           "koa-router": "^10.0.0",
           "mysql": "^2.18.1"
         }
  • test.js

        const Koa = require("koa")
        const Router = require("koa-router")
        const mysql = require("mysql")
        const koaNunjucks = require(&#39;koa-nunjucks-2&#39;);
        const path = require(&#39;path&#39;);

        const app = new Koa();
        const router = new Router();

        // mysqljs 连接 mysql数据库
        let connection = mysql.createConnection({
            host: &#39;127.0.0.1&#39;, // mysql所在的主机,本地的话就是 127.0.0.1 或者 localhost, 如果数据库在服务器上,就写服务器的ip
            user: &#39;root&#39;, // mysql的用户名 默认root
            password: &#39;mysql密码&#39;, // mysql的密码
            database: &#39;db1&#39; // 你要连接那个数据库
        })

        // 连接 mysql
        connection.connect(err=>{
            // err代表失败
            if(err) {
                console.log("数据库初始化失败");
            }else {
                console.log("数据库初始化成功");
            }
        })

        // 因为 mysqljs不支持 Promise方式CRUD数据
        // 所以我们做一个简单的封装
        function resDb(sql, params) {
            return new Promise((resolve,reject) => {
                let sqlParamsList = [sql]
                if(params) {
                    sqlParamsList.push(params)
                }
                connection.query(...sqlParamsList, (err,res) => {
                    if(err) {
                        reject(err)
                    }else {
                        resolve(res)
                    }
                })
            })
        }

         // 注入 nunjucks 模板引擎
         app.use(koaNunjucks({
            ext: &#39;html&#39;, // html文件的后缀名
            path: path.join(__dirname, &#39;views&#39;), // 视图文件放在哪个文件夹下
            nunjucksConfig: {
              trimBlocks: true // 自动去除 block/tag 后面的换行符
            }
          }));

        //请求 /userAll 的时候返回数据
        router.get("/userAll", async ctx => {
            const userAll = await resDb("SELECT * FROM user")
            await ctx.render("table",{userAll})
        })

        //请求 /addUser 接受前端传过来的数据,并且把数据持久化到数据库中
        router.get("/addUser", async ctx => {
            const { name, age } = ctx.query
            // 判断 name 和 age是否有值,都有值时,数据存入数据库,刷新表格页面
            // 否则直接返回到表格页面
            if(name && age) {
            await resDb("INSERT INTO user values(null,?,?)",[name, age])
            }
            //重定向路由,到 userAll
            ctx.redirect("/userAll")
        })

        //请求 /updateUser 接受前端传过来的数据,并且把数据持久化到数据库中
        router.get("/updateUser", async ctx => {
            const { id, name, age } = ctx.query
            // 判断 id, name 和 age是否有值,都有值时,更新数据库中的数据,刷新表格页面
            // 否则直接返回到表格页面
            if(id, name && age) {
            await resDb("UPDATE user SET name=?, age=? WHERE id=?",[name, age, id])
            }
            //重定向路由,到 userAll
            ctx.redirect("/userAll")
        })

        //请求/delete/:id  接受前端传过来的数据,并且把对应的id的数据删掉
        router.get("/delete/:id", async ctx => {
            const { id } = ctx.params
            // 判断 id否有值,有值时,根据id删除数据库中的数据,刷新表格页面
            // 否则直接返回到表格页面
            if(id) {
            await resDb("DELETE FROM user WHERE id=?",[id])
            }
            //重定向路由,到 userAll
            ctx.redirect("/userAll")
        })

        //测试代码
        router.get("/hello", ctx => {
            ctx.body = "hello"
        })


        app
        .use(router.routes())
        .use(router.allowedMethods())
        .listen(3333,()=>{
            console.log("server running port:" + 3333);
        })
  • views/table.html

      <!DOCTYPE html>
          <html>
    
          <head>
              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Document</title>
              <style>
                  .table {
                      width: 500px;
                  }
    
                  td {
                      text-align: center;
                  }
              </style>
          </head>
    
              <body>
                  <form action="/addUser" autocomplete="off">
                      <label for="name">
                          用户名:
                          <input type="text" name="name" placeholder="请输入用户名">
                      </label>
                      <label for="age">
                          年龄:
                          <input type="number" name="age" min="0" placeholder="请输入年龄">
                      </label>
                      <input type="submit" value="添加">
                  </form>
                  <form action="/updateUser" autocomplete="off">
                      <label for="id">
                          id:
                          <input type="number" name="id" placeholder="请输入要更新的ID">
                      </label>
                      <label for="name">
                          用户名:
                          <input type="text" name="name" placeholder="请输入用户名">
                      </label>
                      <label for="age">
                          年龄:
                          <input type="number" name="age" min="0" placeholder="请输入年龄">
                      </label>
                      <input type="submit" value="修改">
                  </form>
                  <table border="1" cellspacing="0">
                      <thead>
                          <tr>
                              <th>id</th>
                              <th>姓名</th>
                              <th>年龄</th>
                              <th>操作</th>
                          </tr>
                      </thead>
                      <tbody>
                          {% for user in userAll %}
                          <tr>
                              <td>{{user.id}}</td>
                              <td>{{user.NAME}}</td>
                              <td>{{user.age}}</td>
                              <td>
                                  <a href={{&#39;/delete/&#39;+user.id}}>删除</a>
                              </td>
                          </tr>
                          {% endfor %}
                      </tbody>
                  </table>
              </body>
          </html>

7、写在最后

  • 当你看到这里的时候,首先你是个很有毅力的人,这篇文章没有插图,全都是代码实现以及页面截图,从头看到尾的话给自己点个赞吧

  • 这篇文章详细的介绍了nodejs连接mysql数据库,并且实现基于模板引擎的增删改查功能,以及对数据库返回结果简单的做了一个promise封装,也对koa及其实例中用到的插件做了相关的介绍

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to use Nodejs to connect to Mysql and implement basic add, delete, modify and query operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools