How to use the MySQL module to operate the database in the front-end project?

If you want to operate the database in the project, you must first install the third-party module (mysql) for operating the MySQL database, use the mysql module to connect to the MySQL database, and execute SQL statements. The specific process is shown in the figure below.

Manipulate the database step in the project

Install and configure the mysql module

  1. Install the mysql module

The mysql module is a third-party module hosted on npm. It provides the ability to connect and manipulate MySQL databases in Node.js projects. To use it in a project, you need to run the following command first to install mysql as a dependency package of the project:

npm install mysql
  1. Configure the mysql module

Before using the mysql module to operate the MySQL database, the mysql module must be configured first. The main configuration steps are as follows:

// 1.导入mysq1模块
const mysql = require('mysql')
// 2.建立与 MySQL数据库的连接
const db = mysql.createPool({
    
    
  host: '127.0.0.1',      //数据库的IP地址
  user: 'root',           //登录数据库的账号
  password:‘admin123',  //登录数据库的密码
  database:‘my_db_01'    //指定要操作哪个数据库
}
  1. Test whether the mysql module works properly

Call the db.query() function, specify the SQL statement to be executed, and get the execution result through the callback function:

//检测mysq1模块能否正常工作
db.query('SELECT 1', (err, results) => {
    
    
   if (err) return console.log(err.message)
   //只要能打印出[RowDataPacket{
    
    '1':1}]的结果,就证明数据库连接正常
   console.log(results)
})

Use the mysql module to operate the MySQL database

  1. Query data

Query all the data in the users table

//查询users表中所有的用户数据
db.query('SELECT * FROM users', (err, results) => {
    
    
    //查询失败
    if (err) return console.log(err.message)
    //查询成功
    console.log(results)
}
  1. insert data

Add new data to the users table, where username is Spider-Man and password is pcc321. The sample code is as follows:

// 1. 要插入到users表中的数据对象
const user = {
    
     username: 'Spider-Man', password: 'pcc321' }
// 2. 待执行的 SQL 语句,其中英文的? 表示占位符
const sqlStr = 'INSERT INTO users (username, password) VALUES (?, ?)'
// 3. 使用数组的形式,依次为?占位符指定具体的值
db.query(sqlStr, [user.username, user.password], (err, results) =» {
    
    
   if(err)return console.log(err.message)//失败
   if(results.affectedRows=== 1) {
    
     console.log('插入数据成功') } // 成功
})
  1. A convenient way to insert data

When adding data to a table, if each attribute of the data object corresponds to the field of the data table, the data can be quickly inserted in the following way:

// 1. 要插入到users表中的数据对象
const (vser = {
    
     username: 'Spider-Man2', password: 'pcc4321'}
// 2. 待执行的SQL语句,其中英文的?表示占位符
const sqlStr = 'INSERT INTO users SET ?'
// 3. 直接将数据对象当作占位符的值
db.query(sqlStr, user, (err, results) => {
    
    
   if(err)return console.log(err.message)//失败
   if(results.affectedRows===1){
    
    console.log('插入数据成功')}//成功
})
  1. update data

The data in the table can be updated in the following ways:

// 1.要更新的数据对象
const user = {
    
     id: 7, username: 'aaa', password: '000' }
// 2.要执行的SQL 语句
const sqlStr = 'UPDATE users SET username=?, password=? WHERE id=?'
// 3.调用db.query()执行 SQL 语句的同时,使用数组依次为占位符指定具体的值
db.query(sqlStr, [user.username, user.password, user.id], (err, results) => {
    
    
   if(err)return console.log(err.message) // 失败
   if(results.affectedRows===1){
    
    console.log('更新数据成功!')}//成功
})
  1. A convenient way to update data

When updating table data, if each attribute of the data object corresponds to the field of the data table, the table data can be quickly updated in the following ways:

// 1. 要更新的数据对象
const user = {
    
     id: 7, username: 'aaaa', password: '0000' }
// 2. 要执行的 SQL 语句
const sqlStr = 'UPDATE users SET ? WHERE id=?'
// 3. 调用db.query()执行 SQL 语句的同时,使用数组依次为占位符指定具体的值
db.query(sqlStr,[user,user.id],(err,results) =>{
    
    
   if(err)return console.log(err.message)//失败
   if(results.affectedRows === 1) {
    
    console.log('更新数据成功!') } //成功
})
  1. delete data

When deleting data, it is recommended to delete the corresponding data according to the unique identifier such as id. Examples are as follows:

// 1.要执行的 SQL 语句
const sqlStr = 'DELETE FROM users WHERE id=?'
// 2.调用 db.query()执行 SQL语句的同时,为占位符指定具体的值
// 注意:如果SQL语句中有多个占位符,则必须使用数组为每个占位符指定具体的值
//        如果SQL语句中只有一个占位符,则可以省略数组
db.query(sqlStr, 7, (err, results) => {
    
    
   if(err)return console.log(err.message)//失败
   if(results.affectedRows ===1){
    
    console.log('删除数据成功!)}//成功
})
  1. mark for deletion

Using the DELETE statement will actually delete the data from the table. To be on the safe side, it is recommended to use the form of marking deletion to simulate the deletion action.

The so-called mark deletion is to set a status field like status in the table to mark whether the current piece of data is deleted.

When the user executes the delete action, we do not execute the DELETE statement to delete the data, but execute the UPDATE statement to mark the status field corresponding to this data as deleted.

//标记删除:使用 UPDATE 语句替代 DELETE语句;只更新数据的状态,并没有真正删除
db.query('UPDATE USERS SET status=1 WHERE id=?', 6, (err, results) =>(
  if(err)return console.log(err.message)//失败
  if(results.affectedRows === 1){
    
    console.log('删除数据成功!')}//成功
})

Guess you like

Origin blog.csdn.net/cz_00001/article/details/131212890