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

青灯夜游
Release: 2021-06-16 18:02:48
forward
8370 people have browsed it

This article will introduce to you how to useNodejsto 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); })
    Copy after login

    • Execute

      node test.jsornodemon test.jsin the project root directory Starting the project

    • Using

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

    • Use

      nodemonto start the project,nodemonwill monitor the files in the startup directory, if any files change,nodemonThe node application will be automatically restarted. It is strongly recommended to usenodemonto 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);
    Copy after login

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); })
    Copy after login

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

       const selectSql = "SELECT * FROM user" connection.query(selectSql, (err,res) => { if(err) console.log(err); console.log(res); })
      Copy after login

  • 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") })
    Copy after login

    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('koa-nunjucks-2'); const path = require('path'); // 注入 nunjucks 模板引擎 app.use(koaNunjucks({ ext: 'html', // html文件的后缀名 path: path.join(__dirname, 'views'), // 视图文件放在哪个文件夹下 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}) })
    Copy after login
    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
  •       Document  
    
    {% for user in userAll %} {% endfor %}
    id 姓名 年龄
    {{user.id}} {{user.NAME}} {{user.age}}
    Copy after login

  • 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页面的添加部分写完

    Copy after login
  • 这个时候页面是长这样的

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") })
    Copy after login
  • 为了提高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) } }) }) }
    Copy after login
  • 升级之后的这个方法适合 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页面改造一下

    Copy after login
  • 下面我们看下后台的代码

    //请求 /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") })
    Copy after login
  • 代码逻辑和新增部分的逻辑是一样的,

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

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

5、通过id删除单条数据

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

     {% for user in userAll %}  {% endfor %} 
    id 姓名 年龄 操作
    {{user.id}} {{user.NAME}} {{user.age}} 删除
    Copy after login
  • 看下页面效果

    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") })
    Copy after login
  • 到目前为止对表格的增删改查(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" }
    Copy after login
  • test.js

const Koa = require("koa") const Router = require("koa-router") const mysql = require("mysql") const koaNunjucks = require('koa-nunjucks-2'); const path = require('path'); const app = new 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的用户名 默认root password: 'mysql密码', // mysql的密码 database: 'db1' // 你要连接那个数据库 }) // 连接 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: 'html', // html文件的后缀名 path: path.join(__dirname, 'views'), // 视图文件放在哪个文件夹下 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); })
Copy after login
  • views/table.html

          Document  
    
    {% for user in userAll %} {% endfor %}
    id 姓名 年龄 操作
    {{user.id}} {{user.NAME}} {{user.age}} 删除
    Copy after login

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!

source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!