NodeJs 简单的使用 MySQL2 扩展包的项目示例

安装依赖包
mysql2插件官网:https://github.com/sidorares/node-mysql2
更详细的文档需移步mysql插件官网:https://github.com/mysqljs/mysql

npm install mysql2

数据库配置文件(config/database.js)

// 文件路径:config/database.js

module.exports = {
    // 数据库类型
    'type': 'mysql',
    // 服务器地址
    'hostname': '127.0.0.1',
    // 数据库名
    'database': 'db_test',
    // 用户名
    'username': 'root',
    // 密码
    'password': '123456',
    // 端口
    'hostport': '3306',
    // 数据库连接参数
    'params': [],
    // 数据库编码默认采用utf8/utf8mb4
    'charset': 'utf8mb4',
}

数据库连接池文件(utils/db_connection.js)

// 文件路径:utils/db_connection.js
/**
 * 数据库连接池
 */
const nm_mysql = require('mysql2/promise');

const databaseConfig = require('../config/database.js');

const connPool = nm_mysql.createPool({
    user: databaseConfig.username,
    password: databaseConfig.password,
    host: databaseConfig.hostname,
    port: databaseConfig.port,
    charset: databaseConfig.charset,
    database: databaseConfig.database
})

// 进程退出时自动关闭连接池
process.on('exit', async (code) => {
    try {
        await connPool.end()
    } catch (error) {

    }
})
module.exports = {
    connPool,
    databaseConfig
};

数据库通用操作文件(utils/db_utils.js)

// 文件路径:utils/db_utils.js
/**
 * 数据库通用操作文件
 */
const {
    connPool,
    databaseConfig
} = require('./db_connection.js')

/**
 * 返回所有数据表
 * @param {String} dbname
 * @param {String} tablename
 * @return array TABLE_NAME, TABLE_TYPE, ENGINE, DATA_LENGTH, CREATE_TIME, TABLE_COLLATION, TABLE_COMMENT
 */
async function getTables(dbName, tablename = '') {
    if (!dbName) {
        dbName = databaseConfig.database;
    }
    let sql = `select TABLE_NAME, TABLE_TYPE, ENGINE, DATA_LENGTH, CREATE_TIME, TABLE_COLLATION, TABLE_COMMENT 
        from information_schema.tables where TABLE_SCHEMA=? AND TABLE_TYPE='BASE TABLE'`;
    const [rows, fields] = await connPool.query(sql, [dbName]);
    return rows;
}

/**
 * 返回所有列
 * @param {String} dbname
 * @param {String} tablename
 * @param {Boolean} withKeyName
 * @return array COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE,
 *      EXTRA, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY, COLUMN_COMMENT
 */
async function getFields(dbName, tableName, withKeyName = false) {
    if (!dbName) {
        dbName = databaseConfig.database;
    }
    let sql = `select COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, COLUMN_TYPE, IS_NULLABLE, EXTRA, DATA_TYPE, 
        CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, COLUMN_KEY, COLUMN_COMMENT from 
        information_schema.columns WHERE TABLE_SCHEMA=? AND TABLE_NAME=? order by ORDINAL_POSITION`
    const [rows, fields] = await connPool.query(sql, [dbName, tableName]);
    return rows;
}

module.exports = {
    getTables,
    getFields,
    connPool,
    databaseConfig
}

主文件(main.js)

// 文件路径:main.js

const nm_fs = require('fs');
const nm_path = require('path');
const dbUtils = require('./utils/db_utils.js')

// 普通查询测试
async function test() {
    const rows = await dbUtils.getTables('');
    console.log(rows);
}

// 事务测试
async function testTrans() {
    // 创建连接
    let conn = await dbUtils.connPool.getConnection();
    // 开启事务
    await conn.beginTransaction();
    try {
        const [rows] = await conn.execute('select * from pedm_auth_admin')
        if (rows.length > 0) {
            const userName = rows[0].user_name;
            // 必然正确的命令
            await conn.execute('update pedm_auth_admin set updated_at=?,login_count=login_count+1 where user_name=?', [new Date().getTime() / 1000, userName]);
            // 必然出错的命令
            // await conn.execute('update pedm_auth_admin set updated_at=?,login_count=login_count+error where user_name=?', [new Date().getTime() / 1000, userName]);
        }
        // 提交事务
        await conn.commit();
        console.log('事务成功提交');
    } catch (error) {
        // 回滚事务
        conn.rollback();
        console.log('事务回滚', error.sqlMessage, error);

    }
    // 释放连接
    conn.release();
}

// 执行
// test();
testTrans();

运行

node main.js
posted on 2021-01-18 20:33  sochishun  阅读(1543)  评论(0编辑  收藏  举报