npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mm_mysql

v2.2.5

Published

这是超级美眉mysql帮助函数模块,用于便捷操作mysql,使用await方式,可以避免嵌套函数

Readme

mm_mysql

一个简洁、高效的Node.js MySQL操作库,支持async/await语法,提供直观的API和强大的功能扩展。

npm version GitHub issues GitHub license

安装

npm install mm_mysql

基本使用

const { Mysql } = require('mm_mysql');

// 创建mysql实例
const mysql = new Mysql({
  host: "localhost",
  port: 3306,
  user: "root",
  password: "your_password",
  database: "your_database"
});

// 打开连接(不需要调用init()方法)
await mysql.open();

// 获取数据库管理器并设置表名
const db = mysql.db().new('users', 'id');

// 执行操作...

// 使用完后关闭连接
await mysql.close();

主要特性

  • 支持async/await语法,避免回调地狱
  • 提供简洁直观的API接口
  • 内置事务支持
  • 自动类型推断的表创建功能(支持int、float、varchar、text、datetime、date、time、boolean等多种数据类型)
  • 灵活的查询条件支持
  • 支持连接池管理
  • 调试模式支持

API文档

Mysql类

构造函数

new Mysql(config)

参数说明:

  • config {Object} 数据库配置对象

配置参数

const config = {
  host: "127.0.0.1",          // 服务器地址
  port: 3306,                 // 端口号
  user: "root",              // 连接用户名
  password: "password",       // 连接密码
  database: "dbname",        // 数据库名
  charset: "utf8mb4",         // 字符集
  timezone: "+08:00",         // 时区
  connect_timeout: 20000,      // 连接超时时间(毫秒)
  connection_limit: 10,        // 连接池大小
  acquire_timeout: 20000,      // 获取连接超时时间(毫秒)
  wait_for_connections: true   // 是否等待连接
};

主要方法

open()

打开数据库连接

  • 返回:{Promise} 连接结果
close()

关闭数据库连接

  • 返回:{Promise} 关闭结果
run(sql, params)

执行查询SQL语句

  • sql {String} SQL语句
  • params {Array} 参数数组(可选)
  • 返回:{Promise} 查询结果数组
exec(sql, params)

执行非查询SQL语句(增删改)

  • sql {String} SQL语句
  • params {Array} 参数数组(可选)
  • 返回:{Promise} 执行结果对象,包含insertId、affectedRows和changedRows等信息
read(table, condition, options)

读取表数据

  • table {String} 表名
  • condition {Object} 查询条件(可选)
  • options {Object} 选项配置(可选)
  • 返回:{Promise} 查询结果
db()

获取数据库管理器

  • 返回:{DB} 数据库管理器实例
beginTransaction()

开始事务

  • 返回:{Promise} 事务连接对象,包含connection、commit、rollback方法
transaction(callback)

执行事务

  • callback {Function} 事务回调函数,接收事务连接作为参数
  • 返回:{Promise} 回调函数的返回结果
getConn()

获取数据库连接(内部使用)

  • 返回:{Promise} 数据库连接对象
getPoolStats()

获取连接池状态信息

  • 返回:{Object} 连接池状态对象
healthCheck()

健康检查

  • 返回:{Promise} 健康检查结果
init()

初始化MySQL服务(兼容性方法)

  • 返回:{Promise}

DB类方法

createTable(model, options)

自动创建数据库表,支持多种数据类型推断

  • model {Object} 模型对象,包含表名和字段定义
    • table {String} 表名
    • fields {Object} 字段定义,支持以下数据类型:
      • 数字类型(自动推断为INT/FLOAT)
      • 字符串类型(自动推断为VARCHAR/TEXT/DATE/DATETIME/TIME)
      • 布尔类型(自动推断为TINYINT(1))
      • Date对象(自动推断为DATETIME)
      • 时间戳(自动推断为DATETIME)
  • options {Object} 选项配置(可选)
    • primary_key {String} 主键字段名(可选)
    • if_not_exists {Boolean} 是否仅当表不存在时创建(可选,默认为true)
  • 返回:{Promise} 执行结果

new(table, key)

创建数据库表管理器

  • table {String} 表名
  • key {String} 主键名(可选,默认为{table}_id)
  • 返回:{DB} 数据库表管理器实例

add(data)

添加数据

  • data {Object} 数据对象
  • 返回:{Promise} 插入的ID

get(where, options)

获取数据

  • where {Object} 条件对象(可选)
  • options {Object} 选项配置(可选)
  • 返回:{Promise} 查询结果

set(data, where)

更新数据

  • data {Object} 数据对象
  • where {Object} 条件对象(可选)
  • 返回:{Promise} 影响行数

del(where)

删除数据

  • where {Object} 条件对象(可选)
  • 返回:{Promise} 影响行数

exec(sql, params)

执行SQL语句

  • sql {String} SQL语句
  • params {Array} 参数数组
  • 返回:{Promise} 执行结果

run(sql, params)

执行查询SQL语句

  • sql {String} SQL语句
  • params {Array} 参数数组
  • 返回:{Promise} 查询结果

事务操作

beginTransaction()

开始事务

  • 返回:{Promise} 事务连接对象,包含connection、commit、rollback方法和_is_ended状态检查

transaction(callback)

执行事务

  • callback {Function} 事务回调函数,接收事务连接对象作为参数
  • 返回:{Promise} 回调函数的返回结果

事务连接对象包含以下方法:

  • connection {Object} - 数据库连接对象
  • commit() {Function} - 提交事务
  • rollback() {Function} - 回滚事务
  • _is_ended() {Function} - 检查事务是否已结束

Mysql管理器

mysqlAdmin(scope, config)

获取Mysql管理器实例

  • scope {String} 作用域名称(可选,默认为'sys')
  • config {Object} 配置参数
  • 返回:{Mysql} Mysql实例

使用示例:

const { mysqlAdmin } = require('mm_mysql');

async function example() {
  // 获取默认作用域的Mysql实例
  const mysql1 = mysqlAdmin('default', {
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'test'
  });
  
  // 获取另一个作用域的Mysql实例
  const mysql2 = mysqlAdmin('backup', {
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'backup_db'
  });
  
  await mysql1.open();
  await mysql2.open();
  
  // 使用实例...
  
  await mysql1.close();
  await mysql2.close();
}

使用示例

表创建示例

const { Mysql } = require('mm_mysql');

async function createTableExample() {
  const mysql = new Mysql({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "test"
  });
  
  await mysql.open();
  
  try {
    // 创建数据库表管理器
    const db = mysql.db();
    
    // 定义表模型
    const userModel = {
      table: 'users',
      fields: {
        id: 1,                 // 整数类型 -> INT
        username: 'test',      // 字符串类型 -> VARCHAR(255)
        email: '[email protected]', // 字符串类型 -> VARCHAR(255)
        age: 25,               // 整数类型 -> INT
        salary: 5000.50,       // 浮点数类型 -> FLOAT
        active: true,          // 布尔类型 -> TINYINT(1)
        birth_date: '2000-01-01', // 日期字符串 -> DATE
        bio: '这是一个很长的个人简介...', // 长字符串 -> TEXT
        created_at: '2023-01-01 12:00:00', // 日期时间字符串 -> DATETIME
        login_time: new Date(), // Date对象 -> DATETIME
        last_active: Date.now() // 时间戳 -> DATETIME
      }
    };
    
    // 创建表
    const result = await db.createTable(userModel, {
      primary_key: 'id',
      if_not_exists: true
    });
    
    console.log('表创建成功:', result);
    
  } catch (error) {
    console.error('创建表失败:', error);
  } finally {
    await mysql.close();
  }
}

createTableExample().catch(console.error);

基本查询操作

const { Mysql } = require('mm_mysql');

async function main() {
  const mysql = new Mysql({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "test",
    debug: true
  });
  
  await mysql.open();
  
  // 执行查询
  const users = await mysql.run('SELECT * FROM users WHERE age > ?', [20]);
  console.log(users);
  
  // 添加数据
  const result = await mysql.exec('INSERT INTO users (name, age) VALUES (?, ?)', ['张三', 25]);
  console.log('Inserted ID:', result.insertId);
  console.log('Affected rows:', result.affectedRows);
  
  // 使用db管理器
  const db = mysql.db().new('users', 'id');
  const newId = await db.add({name: '李四', age: 26});
  console.log('New user ID:', newId);
  
  await db.close();
  await db.destroy();
}

main().catch(console.error);

使用DB类的完整示例

const { Mysql } = require('mm_mysql');

async function dbClassExample() {
  const mysql = new Mysql({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "test"
  });
  
  await mysql.open();
  
  try {
    // 创建DB实例
    const db = mysql.db().new('users', 'id');
    
    // 添加数据
    const newId = await db.add({name: '王五', age: 30, email: '[email protected]'});
    console.log('New user ID:', newId);
    
    // 获取数据
    const user = await db.get({id: newId});
    console.log('User:', user);
    
    // 更新数据
    const updatedRows = await db.set({age: 31, email: '[email protected]'}, {id: newId});
    console.log('Updated rows:', updatedRows);
    
    // 删除数据
    const deletedRows = await db.del({id: newId});
    console.log('Deleted rows:', deletedRows);
    
  } finally {
    await mysql.close();
  }
}

dbClassExample().catch(console.error);

事务操作示例

const { Mysql } = require('mm_mysql');

async function transactionExample() {
  const mysql = new Mysql({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "test"
  });
  
  await mysql.open();
  
  try {
    // 使用transaction方法执行事务
    const result = await mysql.transaction(async (transaction) => {
      // 在事务中执行多个操作
      const insertResult1 = await transaction.connection.execute('INSERT INTO users (name, age) VALUES (?, ?)', ['赵六', 35]);
      const insertResult2 = await transaction.connection.execute('INSERT INTO users (name, age) VALUES (?, ?)', ['孙七', 40]);
      
      // 如果都成功,返回结果
      return { user1: insertResult1[0].insertId, user2: insertResult2[0].insertId };
    });
    
    console.log('Transaction succeeded:', result);
    
  } catch (error) {
    console.error('Transaction failed:', error);
  } finally {
    await mysql.close();
  }
}

transactionExample().catch(console.error);

注意事项

  1. 使用前请确保已正确配置数据库连接信息
  2. 建议使用try-catch处理可能出现的错误
  3. 在程序结束时调用close()关闭数据库连接
  4. 使用事务时,记得正确处理事务的提交和回滚
  5. 查询条件支持多种格式:
    • _min: 大于等于
    • _max: 小于等于
    • _not: 不等于
    • _has: IN查询
    • _like: LIKE查询
  6. createTable方法会根据字段值自动推断数据类型,如需更精确的类型控制,建议直接使用SQL语句
  7. 连接池模式下,建议使用mysqlAdmin方法获取实例以确保线程安全
  8. 支持连接池状态监控和健康检查,可用于系统监控
  9. 基于mysql2/promise模块,支持async/await语法

更新日志

v2.3.0

  • 基于mysql2/promise模块重构,提供更好的性能和稳定性
  • 改进连接池管理,支持连接池状态监控
  • 优化事务处理机制,提供更安全的事务管理
  • 新增健康检查功能,支持连接状态监控
  • 新增mysqlAdmin管理器,支持线程安全的实例管理
  • 改进错误处理机制,提供更详细的错误信息
  • 优化配置参数,支持更多mysql2原生配置选项

v2.2.0

  • 新增createTable方法,支持多种数据类型自动推断
  • 支持boolean类型自动转换为TINYINT(1)
  • 支持date字符串自动识别为DATE类型
  • 支持Date对象自动识别为DATETIME类型
  • 支持时间戳自动识别为DATETIME类型

许可证

ISC License

贡献

欢迎提交Issue和Pull Request!

联系方式

如有问题或建议,请通过以下方式联系: