[Nodejs] Operate mysql database

insert image description here

1. mysql introduction


Paid commercial databases:

  • Oracle, a typical tall, rich and handsome;
  • SQL Server, Microsoft's own products, Windows customized special funds;
  • DB2, IBM's product, sounds quite high-end;
  • Sybase used to be a good friend with Microsoft, but the relationship broke down later, and now the family is miserable.

These databases are not open source and paid. The biggest advantage is that if you spend money, you can find the manufacturer to solve the problem. However, in the world of the Web, it is often necessary to deploy thousands of database servers. Therefore, whether it is Google, Facebook, or domestic BAT, they all choose free open source databases without exception:

  • MySQL, everyone is using it, generally you can’t go wrong;
  • PostgreSQL, a bit academic, is actually quite good, but not as well-known as MySQL;
  • sqlite, an embedded database, suitable for desktop and mobile applications.

As a JavaScript full-stack engineer, which free database should I choose? Of course MySQL. Because MySQL has the highest penetration rate, if something goes wrong, it is easy to find a solution. Moreover, there are a lot of monitoring and operation and maintenance tools around MySQL, which are easy to install and use.
insert image description here

2. Differences from non-relational databases


The main difference between relational and non-relational databases is the way data is stored. Relational data is inherently tabular and thus stored in rows and columns of a data table. Data tables can be associated with each other and stored collaboratively, and it is also easy to extract data.

In contrast, non-relational data does not fit into rows and columns of tables, but is grouped together in large chunks. Non-relational data is usually stored in datasets, like documents, key-value pairs, or graph structures. Your data and its characteristics are the number one influencing factor in choosing how to store and extract your data.

The most typical data structure of a relational database is a table, a data organization composed of two-dimensional tables and their connections. Advantages:

  • Easy to maintain: all use the table structure and the format is consistent;
  • Easy to use: SQL language is common and can be used for complex queries;
  • Complex operations: Support SQL, which can be used for very complex queries between one table and multiple tables.
    • Disadvantages:
      ① Poor read and write performance, especially high-efficiency read and write of massive data;
      ② Fixed table structure, less flexibility;
      ③ High concurrent read and write requirements. For traditional relational databases, hard disk I/O is a Big bottleneck.

Strictly speaking, a non-relational database is not a database. It should be a collection of data structured storage methods, which can be documents or key-value pairs.

advantage:

  • Flexible format: The format of stored data can be in the form of key, value, document, picture, etc. It is flexible to use and has a wide range of application scenarios, while relational databases only support basic types.
  • Fast speed: nosql can use hard disk or random access memory as a carrier, while relational database can only use hard disk;
  • High scalability;
  • Low cost: nosql databases are easy to deploy and are basically open source software.

shortcoming:

  • Does not provide sql support;
  • no transactions;
  • The data structure is relatively complex, and the complex query is slightly lacking.

3. History of MySQL2 and reasons for its selection


The MySQL2 project is a continuation of MySQL-Native . Protocol parser code rewritten from scratch, api changed to match popular mysqljs/mysql . The MySQL2 team is working with the mysqljs/mysql team to factor out and move the shared code under the mysqljs organization.

Most APIs of MySQL2 are compatible with mysqljs and support most functions. MySQL2 also provides more additional functions

MySQL2 is cross-platform and can be installed on Linux, Mac OS or Windows without a doubt.

npm install --save mysql2

4. Connect to the database


config/db.config.js

const mysql = require('mysql2/promise')

// 通过createPool方法连接服务器
const db = mysql.createPool({
    
    
  host: '127.0.0.1', // 表示连接某个服务器上的mysql数据库
  user: 'root', // 数据库的用户名 (默认为root)
  password: '123456', // 数据库的密码 (默认为root)
  database: 'dbtest11', // 创建的本地数据库名称
})

// 测试数据库是否连接成功
db.getConnection((err, conn) => {
    
    
  conn.connect(err => {
    
    
    if (err) {
    
    
      console.log('连接失败~')
    } else {
    
    
      console.log('连接成功~')
    }
  })
})

module.exports = db

5. Query


  • import mysql
  • Connect the mysql database to the server through the createPool method and declare a db variable
  • Test whether the connection is successful through the db.query method
  • return data to the client
    • import express
    • create server
    • start server
    • register route
    • Execute sql statements through db.query (query database)
    • If the execution is successful, the data will be responded to the client
var express = require('express')
const db = require('../config/db.config')
var router = express.Router()

// 通过nodejs获取数据库中的数据  并返回给客户端-
router.get('/', async (req, res) => {
    
    
  // 通过db.query方法来执行mysql  测试是否连接成功
  // 查询语句 data 得到的是一个数组,  增删改得到的是受影响的行数
  let users = await db.query('select * from users')
  console.log(users[0])
  res.send({
    
    
    ok: 1,
    data: users[0],
  })
})

module.exports = router

Console output:
insert image description here
Returned data:
image-20221105230828022

6. Insert


// 给user中添加用户名和密码
router.get('/addUser', async (req, res) => {
    
    
  const sql = 'insert into users (userid,department_id) values (?,?)' // 构建sql语句
  // 执行sql语句
  let ret = await db.query(sql, ['Mary', 2])
  console.log(ret)
  res.send({
    
    
    ok: 1,
  })
})

Console output:
image-20221105231625375

7. Modify


// 修改数据
router.get('/updateUser', async (req, res) => {
    
    
  const sql = 'update users set userid=?,department_id=? where id=?' // 构建sql语句
  // 执行sql语句
  let ret = await db.query(sql, ['Jerry', 10, 8])
  console.log(ret)
  res.send({
    
    
    ok: 1,
  })
})

Console output:
image-20221106095506641

8. Delete


// 删除数据
router.get('/deleteUser', async (req, res) => {
    
    
  const sql = 'delete from users where id=?' // 构建sql语句
  // 执行sql语句
  let ret = await db.query(sql, [8])
  console.log(ret)
  res.send({
    
    
    ok: 1,
  })
})

Console output:

image-20221106100105915

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131931757