feat(server): 添加数据库配置和数据库工具类
- 新增 db.config.ts 文件,包含 cdk 和 game 数据库的配置信息 - 新增 db.util.ts 文件,实现数据库连接池和查询功能
This commit is contained in:
17
server/src/config/db.config.ts
Normal file
17
server/src/config/db.config.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export const cdkDbConfig = {
|
||||
host: '192.168.25.110', // MySQL服务器地址
|
||||
user: 'root', // 数据库用户名
|
||||
password: 'mysql_tr2Few', // 数据库密码
|
||||
database: 'cdk', // 数据库名称
|
||||
port: 23306, // MySQL端口号
|
||||
connectionLimit: 10 // 连接池大小
|
||||
};
|
||||
|
||||
export const gameDbConfig = {
|
||||
host: '192.168.25.110', // MySQL服务器地址
|
||||
user: 'root', // 数据库用户名
|
||||
password: 'mysql_tr2Few', // 数据库密码
|
||||
database: 'tafang_game_zjy', // 数据库名称
|
||||
port: 23306, // MySQL端口号
|
||||
connectionLimit: 10 // 连接池大小
|
||||
};
|
||||
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