Node.js connect to mysql database

Table of contents

1. Install the driver

Two, connect to the database

1. Configuration information of database connection

Description of database connection parameters

2. Encapsulate the execution statement of mysql

3. Backend routing file 

3. Database operation ( CURD )

1. Query data

2. Insert data

3. Update data

4. Delete data

4. Get the number of affected rows

5. Get the number of changed rows

6. Multi-statement query

7. Affairs

4. Exception Safety Type Recasting

5. Specific operation demonstration

entry file

backend routing file

database configuration file 

Encapsulate mysql query function

Startup project

Six, view the database

7. Call interface

reference documents


1. Install the driver

npm install mysql
npm install --save mysql2

Mysql compatible upgrade npm package mysql2, mysql2 is compatible with mysql api syntax.

There is not much difference in use, but mysql2 has greatly improved performance.

 

Two, connect to the database

1. Configuration information of database connection

// db.config.js

// 数据库连接配置
module.exports = {
	mysql: {
		host: 'localhost', // 主机地址 (默认:localhost)
		user: 'root', // 数据库用户名
		password: 'root', // 数据库密码
		database: 'schoolmarket', // 数据库名
		port: '3306' // 端口号 (默认:3306)
	}
}

Description of database connection parameters

parameter describe
host Host address (default: localhost)
  user username
  password password
  port port number (default: 3306)
  database Database name
  charset Connection character set (default: 'UTF8_GENERAL_CI', note that the letters of the character set must be capitalized)
  localAddress This IP is used for TCP connections (optional)
  socketPath Link to unix domain path, ignored when host and port are used
  timezone time zone (default: 'local')
  connectTimeout Connection timeout (default: unlimited; unit: milliseconds)
  stringifyObjects Whether to serialize the object
  typeCast Whether to convert column values ​​to native JavaScript type values ​​(default: true)
  queryFormat Custom query statement formatting method
  supportBigNumbers When the database supports bigint or decimal type columns, you need to set this option to true (default: false)
  bigNumberStrings supportBigNumbers and bigNumberStrings enable forcing bigint or decimal columns to be returned as JavaScript string types (default: false)
  dateStrings Force timestamp, datetime, and data types to be returned as strings instead of JavaScript Dates (default: false)
  debug Enable debugging (default: false)
  multipleStatements Whether to allow multiple MySQL statements in a query (default: false)
  flags Used to modify connection flags
  ssl Use the ssl parameter (in the same format as the crypto.createCredenitals parameter) or a string containing the name of the ssl configuration file. Currently, only Amazon RDS configuration files are bundled

 

2. Encapsulate the execution statement of mysql

// db.js

// 使用mysql2
const mysql = require('mysql2');
// 引入mysql配置文件
const dbConfig = require('./db.config');

module.exports = {
    query: function(sql, params, callback) {

        // 每次使用的时候需要创建链接,数据操作完成之后要关闭连接
        const connection = mysql.createConnection(dbConfig)

        connection.connect(function(err) {
            if (err) {
                throw err
            }

            // 执行数据操作
            connection.query(sql, params, function(err, results, fields) {

                if (err) {
                    throw err
                }

                // 将查询出来的数据返回给回调函数
                callback &&
                    callback(
                        results ? JSON.parse(JSON.stringify(results)) : null,
                        fields ? JSON.parse(JSON.stringify(fields)) : null
                    )

                // 停止链接数据库,必须在查询语句后,不然一调用这个方法,就直接停止链接,数据操作就会失败
                connection.end(function(err) {
                    if (err) {
                        console.log('关闭数据库连接失败!')
                        throw err
                    }
                })
            })
        })
    },
}

3. Backend routing file 

// 引入数据库封装对象
var db = require('./db.js');

// 引入express包
var express = require('express');

//创建路由器对象
var router = express.Router();

// 配置路由对象
router.get('/userList', (req, res, next) => {
    // sql查询user表
    db.query('select * from list', [], function(results, fields) {
        // 以json的形式返回
        res.json({ results })
    })
})

 

3. Database operation ( CURD )

1. Query data

connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
       if(error){
          console.log('[SELECT ERROR] - ',error.message);
          return;
       }
 
       console.log('--------------------------SELECT----------------------------');
       console.log(results);
       console.log('------------------------------------------------------------\n\n');  
});
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
       if(error){
          console.log('[SELECT ERROR] - ',error.message);
          return;
       }
 
       console.log('--------------------------SELECT----------------------------');
       console.log(results);
       console.log('------------------------------------------------------------\n\n');  
});

2. Insert data

var  addSql = 'INSERT INTO websites(Id, name, url, alexa, country) VALUES(0,?,?,?,?)';
var  addSqlParams = ['菜鸟', 'https://xxx.com','23453', 'CN'];

// 执行插入数据
connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
         console.log('[INSERT ERROR] - ',err.message);
         return;
        }        
 
       console.log('--------------------------INSERT----------------------------');
       //console.log('INSERT ID:',result.insertId);        
       console.log('INSERT ID:',result);        
       console.log('-----------------------------------------------------------------\n\n');  
});

3. Update data

var modSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?';
var modSqlParams = ['菜鸟', 'https://xxx.com', 6];

// 更新数据
connection.query(modSql,modSqlParams,function (err, result) {
  if(err){
      console.log('[UPDATE ERROR] - ',err.message);
      return;
  }        
  console.log('--------------------------UPDATE----------------------------');
  console.log('UPDATE affectedRows', result.affectedRows);
  console.log('-----------------------------------------------------------------\n\n');
});

4. Delete data

var delSql = 'DELETE FROM websites where id=6';

// 删除数据
connection.query(delSql, function (err, result) {
        if(err){
          console.log('[DELETE ERROR] - ',err.message);
          return;
        }        
 
       console.log('--------------------------DELETE----------------------------');
       console.log('DELETE affectedRows', result.affectedRows);
       console.log('-----------------------------------------------------------------\n\n');  
});

4. Get the number of affected rows

// 从插入、更新或删除语句中获取受影响的行数
connection.query('DELETE FROM posts WHERE title = "wrong"', function (error, results, fields) {
  if (error) throw error;
  console.log('deleted ' + results.affectedRows + ' rows');
})

5. Get the number of changed rows

// 从更新语句中获取更改的行数
// changedRows与affectedRows的不同之处在于,值未更改的更新行不被列入changedRows
connection.query('UPDATE posts SET ...', function (error, results, fields) {
  if (error) throw error;
  console.log('changed ' + results.changedRows + ' rows');
})

6. Multi-statement query

// 多语句查询会被SQL注入,如果确定想使用可以开启
var connection = mysql.createConnection({
    multipleStatements: true
});

7. Affairs

// 开启一个简单的事务
connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
    if (error) {
      return connection.rollback(function() {
        throw error;
      });
    }
 
    var log = 'Post ' + results.insertId + ' added';
 
    connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
      if (error) {
        return connection.rollback(function() {
          throw error;
        });
      }
      connection.commit(function(err) {
        if (err) {
          return connection.rollback(function() {
            throw err;
          });
        }
        console.log('success!');
      });
    });
  });
});

 

4. Exception Safety Type Recasting

By default, the driver will convert mysql types to native JavaScript types.

mysql javascript
TINYINT Number
SMALLINT
INT
MEDIUMINT
YEAR
FLOAT
DOUBLE
TIMESTAMP Date
DATE
DATETIME
TINYBLOB Buffer
MEDIUMBLOB
LUNG BLOB
BLOB
BINARY
VARBINARY
BIT (last byte will be filled with 0 bits as necessary)
char String
varchar
tinytext
mediumtext
longtext
text
enum
set
decimal
bigint
time
geometry

5. Specific operation demonstration

Use express-generator to quickly build a project
 

entry file

// index.js

const userApi = require('./api/myApi');
const fs = require('fs');
const path = require('path');
// body-parser - node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据
const bodyParser = require('body-parser');

// 引入express包
const express = require('express');
// 创建web服务器
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 后端api路由
app.use('/api/user', userApi);

// 监听端口
app.listen(3000);
console.log('success listen at port: 3000......');

backend routing file

// api.js

// 引入封装 mysql 查询函数
var db = require('./db');
// 引入express包
var express = require('express');

// 创建路由器对象
var router = express.Router();


// Multer 是一个 node.js 中间件,用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件
var multer = require('multer');

// 格式化时间模块Silly-datetime
var datetime = require('silly-datetime');

var fs = require('fs');
var path = require('path')
var UUID = require('uuid')

// multer 自定义存储的方式
var storage = multer.diskStorage({  
    // 保存路径
    destination: function (req, file, cb) {
        // 注意这里的文件路径,不是相对路径,直接填写从项目根路径开始写就行了
        cb(null, 'static/public/uploads')  
    },  
    // 保存在 destination 中的文件名
    filename: function (req, file, cb) {  
        var str = file.originalname.split('.');  
        cb(null, UUID.v1() + '.' + str[1]);  
    }  
})

var upload = multer({storage: storage})


// 设置返回response
var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code: '1',
            msg: '操作失败'
        });
    } else {
        console.log('ret', ret)
        res.json(ret);
    }
};

// 增加用户接口
router.post('/addUser', (req, res) => {
  let params = req.body;
  db.query("select * from user where user_id=?", [params.id], function (err, result) {
    if (err) {
      console.log(err);
    }

    if (result) {
      if (result.length > 0) {
        jsonWrite(res, {
          code: -1,
          msg: '该账号已注册!'
        });
      } else {
        db.query("INSERT INTO user(user_id,user_nick,gender,password) VALUES(?,?,?,?)", [params.id, params.nick, params.gender, params.password], function (err, result) {
          if (err) {
            console.log(err);
          }

          if (result) {
            jsonWrite(res, {
              code: 200,
              msg: '注册用户成功!'
            });
          }
        })
      }
    }
  })

});

database configuration file 

// db.config.js

// 数据库连接配置
module.exports = {
	mysql: {
		host: 'localhost', // 主机地址 (默认:localhost)
		user: 'root', // 数据库用户名
		password: 'root', // 数据库密码
		database: 'schoolmarket', // 数据库名
		port: '3306' // 端口号 (默认:3306)
	}
}

Encapsulate mysql query function

// db.js

// 使用mysql2
const mysql = require('mysql2');
// 引入mysql配置文件
const dbConfig = require('./db.config');

module.exports = {
    query: function(sql, params, callback) {

        // 每次使用的时候需要创建链接,数据操作完成之后要关闭连接
        const connection = mysql.createConnection(dbConfig)

        connection.connect(function(err) {
            if (err) {
                throw err
            }

            // 执行数据操作
            connection.query(sql, params, function(err, results, fields) {

                if (err) {
                    throw err
                }

                // 将查询出来的数据返回给回调函数
                callback &&
                    callback(
                        results ? JSON.parse(JSON.stringify(results)) : null,
                        fields ? JSON.parse(JSON.stringify(fields)) : null
                    )

                // 停止链接数据库,必须在查询语句后,不然一调用这个方法,就直接停止链接,数据操作就会失败
                connection.end(function(err) {
                    if (err) {
                        console.log('关闭数据库连接失败!')
                        throw err
                    }
                })
            })
        })
    },
}

 

Startup project

server is the name of the folder of the entry file index.js

node server

Six, view the database

You can use database visualization tools such as navicat premium to view and operate the database.

7. Call interface

You can use a browser or postman to call the interface to check the returned status.

reference documents

Node.js 连接 MySQL | 菜鸟教程

mysql - npm

mysql2 - npm

Guess you like

Origin blog.csdn.net/qq_31851435/article/details/130724518