Query.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { QueryResult } from 'mysql2';
  2. import { pool } from '../config/db';
  3. /**
  4. * 执行SELECT查询
  5. * @param sql SQL查询语句
  6. * @param params 查询参数
  7. * @returns 查询结果
  8. */
  9. export async function query<T extends QueryResult = any>(sql: string, params: any[] = []): Promise<T[]> {
  10. const [rows] = await pool.execute<T>(sql, params);
  11. return rows as T[];
  12. }
  13. export async function queryAndReturnInsertId(sql: string, params: any[] = []) : Promise<number> {
  14. const [rows] = await pool.execute(sql, params);
  15. const [insertIdRows] = await query('SELECT LAST_INSERT_ID() AS id');
  16. return insertIdRows.id;
  17. }
  18. /**
  19. * 执行INSERT查询
  20. * @param sql SQL插入语句
  21. * @param params 查询参数
  22. * @returns 插入结果,包含insertId
  23. */
  24. export async function insert(sql: string, params: any[] = []): Promise<{ insertId: number }> {
  25. const [result] = await pool.execute(sql, params);
  26. return result as { insertId: number };
  27. }
  28. /**
  29. * 执行UPDATE查询
  30. * @param sql SQL更新语句
  31. * @param params 查询参数
  32. * @returns 更新结果,包含affectedRows
  33. */
  34. export async function update(sql: string, params: any[] = []): Promise<{ affectedRows: number }> {
  35. const [result] = await pool.execute(sql, params);
  36. return result as { affectedRows: number };
  37. }
  38. /**
  39. * 执行DELETE查询
  40. * @param sql SQL删除语句
  41. * @param params 查询参数
  42. * @returns 删除结果,包含affectedRows
  43. */
  44. export async function remove(sql: string, params: any[] = []): Promise<{ affectedRows: number }> {
  45. const [result] = await pool.execute(sql, params);
  46. return result as { affectedRows: number };
  47. }
  48. /**
  49. * 执行事务
  50. * @param callback 事务回调函数
  51. * @returns 事务执行结果
  52. */
  53. export async function transaction<T>(callback: (connection: any) => Promise<T>): Promise<T> {
  54. const connection = await pool.getConnection();
  55. try {
  56. await connection.beginTransaction();
  57. const result = await callback(connection);
  58. await connection.commit();
  59. return result;
  60. } catch (error) {
  61. await connection.rollback();
  62. throw error;
  63. } finally {
  64. connection.release();
  65. }
  66. }