33 lines
909 B
TypeScript
33 lines
909 B
TypeScript
|
|
import mysql from 'mysql';
|
||
|
|
import { dbConfig } from '../config/db.config';
|
||
|
|
|
||
|
|
// 创建连接池
|
||
|
|
const pool = mysql.createPool(dbConfig);
|
||
|
|
|
||
|
|
// 获取数据库连接
|
||
|
|
export const getConnection = (): Promise<mysql.PoolConnection> => {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
pool.getConnection((err, connection) => {
|
||
|
|
if (err) {
|
||
|
|
reject(err);
|
||
|
|
} else {
|
||
|
|
resolve(connection);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
};
|
||
|
|
|
||
|
|
// 执行查询
|
||
|
|
export const query = async (sql: string, values?: any[]): Promise<any> => {
|
||
|
|
const connection = await getConnection();
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
connection.query(sql, values, (err, results) => {
|
||
|
|
connection.release(); // 释放连接
|
||
|
|
if (err) {
|
||
|
|
reject(err);
|
||
|
|
} else {
|
||
|
|
resolve(results);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
};
|