unicloud-mysql
v1.0.0
Published
快速操作mysql的TypeScript库
Downloads
10
Readme
unicloud-mysql
快速操作 MySQL 数据库的 TypeScript 库,提供链式调用 API,简化数据库操作。
功能特点
- 提供简洁的链式调用 API
- 支持参数化查询,防止 SQL 注入
- 完整的 TypeScript 类型定义
- 支持基本的 CRUD 操作
- 支持批量插入数据
- 支持自动重连机制
- 完善的错误处理
- 支持模糊查询、排序等常用操作
安装
使用 npm 安装:
npm install unicloud-mysql使用 yarn 安装:
yarn add unicloud-mysql基本使用
引入库
import Database from 'unicloud-mysql';
// 或者使用 CommonJS
const Database = require('unicloud-mysql').default;初始化数据库连接
// 创建数据库连接实例
const db = new Database({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db',
port: 3306 // 可选,默认 3306
});查询数据
// 查询所有用户
const result = await db.table('users').get();
console.log(result);
// 条件查询
const user = await db.table('users').where({ id: 1 }).get();
console.log(user);
// 指定字段查询
const userInfo = await db.table('users').field(['id', 'name', 'email']).where({ id: 1 }).get();
console.log(userInfo);
// 排序查询
const sortedUsers = await db.table('users').sort({ id: 'DESC' }).get();
console.log(sortedUsers);
// 计数查询
const userCount = await db.table('users').count().get();
console.log(userCount);
// 模糊查询
const searchUsers = await db.table('users').like([['name', '张', 'both']]).get();
console.log(searchUsers);
// 查询完成后自动关闭连接
const result = await db.table('users').where({ id: 1 }).get(true); // 传入true自动关闭连接
console.log(result);插入数据
// 插入单条数据
const addResult = await db.table('users').add({
name: '张三',
email: '[email protected]',
age: 25,
created_at: new Date()
}).get();
console.log(addResult);
// 插入单条数据并忽略重复
const addIgnoreResult = await db.table('users').add({
name: '张三',
email: '[email protected]'
}, true).get(); // 第二个参数设为 true 表示忽略重复项
console.log(addIgnoreResult);
// 批量插入数据
const batchAddResult = await db.table('users').addAll([
{
name: '李四',
email: '[email protected]',
age: 28
},
{
name: '王五',
email: '[email protected]',
age: 30
}
]).get();
console.log(batchAddResult);
// 批量插入数据并忽略重复
const batchAddIgnoreResult = await db.table('users').addAll([
{
name: '李四',
email: '[email protected]'
},
{
name: '王五',
email: '[email protected]'
}
], true).get();
console.log(batchAddIgnoreResult);更新数据
// 更新数据
const updateResult = await db.table('users').where({ id: 1 }).update({
name: '张三(已更新)',
age: 26
}).get();
console.log(updateResult);删除数据
// 删除数据
const deleteResult = await db.table('users').where({ id: 1 }).del().get();
console.log(deleteResult);执行自定义 SQL
// 执行自定义 SQL 查询
const customSqlResult = await db.sqlQuery('SELECT * FROM users WHERE age > 25');
console.log(customSqlResult);
// 执行带参数的自定义 SQL(注意:当前版本的 sqlQuery 方法不直接支持参数化查询,建议使用 where 方法)
const customSqlWithParamsResult = await db.table('users').where({ age: 25 }).get();
console.log(customSqlWithParamsResult);关闭数据库连接
// 使用完毕后关闭连接
await db.close();API 文档
Database 类
构造函数
new Database(config: ConnectionConfig)参数:
config: 数据库连接配置,包含 host, user, password, database 等必要字段
table 方法
table(tableName: string): this设置要操作的表名。
参数:
tableName: 表名
field 方法
field(fields: string[]): this设置查询的字段。
参数:
fields: 字段数组
where 方法
where(params: QueryParams): this设置查询条件。
参数:
params: 查询条件对象
like 方法
like(likeArray: LikeItem[]): this设置模糊查询条件。
参数:
likeArray: 模糊查询条件数组,每个元素为 [字段名, 搜索值, 匹配模式],匹配模式可选 'top'、'end'、'both'
sort 方法
sort(params: QueryParams): this设置排序条件。
参数:
params: 排序条件对象,键为字段名,值为 'ASC' 或 'DESC'
count 方法
count(): this执行计数查询。
add 方法
add(params: QueryParams, isIgnore?: boolean): this添加单条数据。
参数:
params: 要添加的数据isIgnore: 是否忽略重复项,默认为 false
addAll 方法
addAll(paramsArray: QueryParams[], isIgnore?: boolean): this批量添加数据。
参数:
paramsArray: 要添加的数据数组isIgnore: 是否忽略重复项,默认为 false
update 方法
update(params: QueryParams): this更新数据。
参数:
params: 要更新的数据
del 方法
del(): this删除数据。
sqlQuery 方法
sqlQuery<T = any>(sql: string, type?: QueryType): Promise<QueryResult<T>>执行自定义 SQL 查询。
参数:
sql: SQL 语句type: 查询类型,可选 'none'、'del'、'add'、'update'、'count'
get 方法
get<T = any>(autoClose?: boolean): Promise<QueryResult<T>>执行查询并获取结果。
参数:
autoClose: 是否在查询完成后自动关闭数据库连接,默认为 false
返回值:
Promise<QueryResult<T>>: 查询结果
close 方法
close(): Promise<void>关闭数据库连接。
类型定义
QueryType
export type QueryType = 'none' | 'del' | 'add' | 'update' | 'count';QueryParams
export interface QueryParams {
[key: string]: any;
}LikeItem
export interface LikeItem {
[0]: string; // 字段名
[1]: string; // 搜索值
[2]?: 'top' | 'end' | 'both'; // 匹配模式
}QueryResult
export interface QueryResult<T = any> {
code: number | string;
msg: string;
data: T;
update?: string;
del?: string;
count?: string;
add?: string;
}ConnectionConfig
export interface ConnectionConfig extends mysql.ConnectionConfig {
// 扩展 mysql 连接配置
}错误处理
所有数据库操作都返回统一的 QueryResult 对象,包含 code、msg 和 data 三个字段。
code: 状态码,0 表示成功,非 0 表示失败msg: 消息,成功时为 'SUCCESS',失败时为错误信息data: 数据,根据操作类型返回不同的数据
常见错误类型:
- 连接失败:code 500,msg '数据库连接失败: xxx'
- 字段值重复:code 500,msg '字段值重复'
- 表不存在:code 500,msg '表不存在'
- 访问被拒绝:code 500,msg '数据库访问被拒绝'
- SQL 语句为空:code 400,msg 'SQL 语句不能为空'
- 参数错误:根据具体情况返回相应的错误信息
安全性考虑
- 该库默认使用参数化查询,避免 SQL 注入攻击
- 对于没有 WHERE 条件的 UPDATE 和 DELETE 操作,会输出警告信息
- 所有输入参数都会进行严格的类型检查
注意事项
- 确保在使用完毕后调用
close()方法关闭数据库连接 - 对于大批量数据操作,建议使用
addAll方法批量插入,提高性能 - 当数据库连接断开时,库会自动尝试重新连接
- 所有操作都必须先通过
table()方法设置表名
许可证
MIT
