feat(server): 添加数据库配置和数据库工具类
- 新增 db.config.ts 文件,包含 cdk 和 game 数据库的配置信息 - 新增 db.util.ts 文件,实现数据库连接池和查询功能
This commit is contained in:
33
server/src/utils/db.util.ts
Normal file
33
server/src/utils/db.util.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user