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_sql

v1.4.1

Published

一个通用的SQL帮助类,支持通过切换db_type实现对不同数据库的操作,包括MySQL和SQLite等

Downloads

518

Readme

mm_sql

一个通用的SQL帮助类,支持通过切换db_type实现对不同数据库的操作,包括MySQL和SQLite等,提供统一的API接口,支持异步操作和基础SQL执行。

安装

npm install mm_sql

依赖

  • mm_mysql: ^2.1.1
  • mm_sqlite: ^1.1.3

使用方法

1. 基本使用

// 引入模块
const { Sql } = require('mm_sql');

// 创建实例(默认使用MySQL)
const sql = new Sql({
  db_type: 'mysql',
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: 'password',
  database: 'test_db'
});

// 执行查询SQL
const users = await sql.run('SELECT * FROM users WHERE status = 1');

// 执行更新SQL
const result = await sql.exec('UPDATE users SET status = 0 WHERE id = 1');

// 关闭连接
await sql.close();

2. 切换数据库类型

// 创建MySQL实例
const sql = new Sql({
  db_type: 'mysql',
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mysql_db'
});

// 切换到SQLite
sql.setConfig({
  db_type: 'sqlite',
  dir: '/db/',
  database: 'sqlite.db'
});

// 使用SQLite进行操作
const data = await sql.run('SELECT * FROM users');

3. 主要方法

SQL执行方法

// 执行查询操作(返回结果集)
const users = await sql.run('SELECT * FROM users WHERE status = 1');

// 执行带参数的查询
const user = await sql.run('SELECT * FROM users WHERE id = ?', [1]);

// 执行带超时的查询
const timeoutResult = await sql.run('SELECT * FROM users WHERE status = 1', [], 5000);

// 执行修改操作(返回影响行数)
const updateResult = await sql.exec('UPDATE users SET status = 0 WHERE id = 1');

// 执行带参数的修改
const updateWithParams = await sql.exec('UPDATE users SET name = ? WHERE id = ?', ['张三', 1]);

// 执行带超时的修改
const timeoutExec = await sql.exec('DELETE FROM users WHERE status = 0', [], 3000);

// 使用对象参数方式调用
const result = await sql.run({
  sql: 'SELECT * FROM users WHERE name LIKE ?',
  params: ['张%'],
  timeout: 5000
});

连接管理方法

// 手动打开数据库连接
await sql.open();

// 手动关闭数据库连接
await sql.close();

// 动态修改配置
sql.setConfig({
  host: 'new_host',
  database: 'new_database'
});

模板方法

// SQL模板查询生成
const query = sql.tplQuery({ name: '张', age: 20 }, {
  name: '`name` LIKE "{0}%"',
  age: '`age` > {0}'
});
// 生成: "`name` LIKE \"张%\" AND `age` > 20"

// SQL模板数据生成
const body = sql.tplBody({ name: '李四', age: 25 }, {
  name: '`name` = {0}',
  age: '`age` = {0}'
});
// 生成: "`name` = '李四', `age` = 25"

// 参数过滤
const filteredParams = sql.filter({ id: 1, name: '张三', password: '123' }, ['password']);
// 结果: { id: 1, name: '张三' }

数据库适配器方法

// 获取底层数据库适配器
const dbAdapter = sql.db();
// 可用于直接操作底层数据库接口
db.table = "user_account";
const user = await db.get({
  user_id: 1
});

4. 配置选项

const sql = new Sql({
  // 数据库类型
  db_type: 'mysql', // 可选值: 'mysql', 'sqlite'
  
  // 作用域配置
  scope: 'sys', // 默认作用域
  
  // MySQL配置
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '',
  database: '',
  
  // SQLite配置
  dir: '/db/', // SQLite数据库文件存储目录
  database: 'db.sqlite' // SQLite数据库文件名
});

高级用法

1. SQL模板

// 定义SQL模板
const sqlTemplate = {
  name: '`name` LIKE "{0}%"',
  age: '`age` > {0}'
};

// 使用模板构建查询条件
const query = sql.tplQuery({ name: '张', age: 20 }, sqlTemplate);
// 生成的查询条件: "`name` LIKE \"张%\" AND `age` > 20"

// 使用模板构建更新语句
const body = sql.tplBody({ name: '李四', age: 25 }, {
  name: '`name` = {0}',
  age: '`age` = {0}'
});
// 生成的更新语句: "`name` = '李四', `age` = 25"

// 使用配置文件定义SQL模板
const config = {
  "query": {
    "name": "`name` like '%{0}%'"
  },
  "where": {
    "uid": "`uid` = {0}"
  },
  "update": {
    "name": "`name` = {0}"
  }
};

// 使用配置文件中的模板
const queryFromConfig = sql.tplQuery({ name: '张' }, config.query);

2. 自定义SQL执行

// 执行自定义查询SQL
const result = await sql.run('SELECT * FROM users WHERE status = 1');

// 执行自定义更新SQL
const updateResult = await sql.exec('UPDATE users SET status = 0 WHERE id = 1');

// 执行带参数的SQL
const user = await sql.run('SELECT * FROM users WHERE id = ?', [1]);

// 执行带超时的SQL
const timeoutResult = await sql.run('SELECT * FROM users WHERE status = 1', [], 5000);

// 执行事务操作(MySQL)
const mysqlTransactionResult = await sql.exec(`
  START TRANSACTION;
  INSERT INTO users (name, age) VALUES ('测试用户', 30);
  UPDATE users SET status = 1 WHERE id = LAST_INSERT_ID();
  COMMIT;
`);

// 执行事务操作(SQLite)
const sqliteTransactionResult = await sql.exec(`
  BEGIN TRANSACTION;
  INSERT INTO users (name, age) VALUES ('测试用户', 30);
  UPDATE users SET status = 1 WHERE id = last_insert_rowid();
  COMMIT;
`);

注意事项

  1. 系统会自动初始化连接,无需手动调用初始化方法
  2. 使用完成后建议调用close()方法关闭连接,避免资源泄漏
  3. 切换数据库类型时会重新创建适配器,原来的连接会被关闭
  4. 不同数据库的SQL语法可能有所差异,请根据实际使用的数据库类型调整SQL语句
  5. 事务操作需要根据具体数据库类型使用相应的SQL语法
  6. 错误处理:所有方法都包含错误处理,会记录错误日志并抛出异常

错误处理

try {
  const result = await sql.run('SELECT * FROM non_existent_table');
} catch (error) {
  console.error('SQL执行失败:', error);
  // 错误信息会被自动记录到日志
}

支持的数据库类型

  • MySQL
  • SQLite

API参考

Sql类

constructor(config)

创建Sql实例

  • config: 配置对象

run(sql, params, timeout)

执行查询SQL

  • sql: SQL语句或选项对象
  • params: 参数数组(可选)
  • timeout: 超时时间(毫秒,可选)

exec(sql, params, timeout)

执行修改SQL

  • sql: SQL语句或选项对象
  • params: 参数数组(可选)
  • timeout: 超时时间(毫秒,可选)

open()

手动打开数据库连接

close()

手动关闭数据库连接

setConfig(config)

动态修改配置

  • config: 新的配置对象

tplQuery(paramDt, sqlDt)

生成SQL查询条件

  • paramDt: 参数对象
  • sqlDt: SQL模板对象

tplBody(paramDt, sqlDt)

生成SQL数据部分

  • paramDt: 参数对象
  • sqlDt: SQL模板对象

filter(paramDt, arr)

过滤参数对象

  • paramDt: 参数对象
  • arr: 需要过滤的键数组

db()

获取底层数据库适配器

许可证

MIT