first commit
This commit is contained in:
64
backend/config/database.js
Normal file
64
backend/config/database.js
Normal file
@@ -0,0 +1,64 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || '123456',
|
||||
database: process.env.DB_NAME || 'score_management',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0
|
||||
});
|
||||
|
||||
// 测试数据库连接
|
||||
async function testConnection() {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
console.log('数据库连接成功');
|
||||
connection.release();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('数据库连接失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行查询
|
||||
async function query(sql, params) {
|
||||
try {
|
||||
const [rows] = await pool.execute(sql, params);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行事务
|
||||
async function executeTransaction(operations) {
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
|
||||
for (const operation of operations) {
|
||||
await connection.execute(operation.sql, operation.params);
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
console.log('事务执行成功');
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
console.error('事务执行失败:', error.message);
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
pool,
|
||||
query,
|
||||
executeTransaction,
|
||||
testConnection
|
||||
};
|
||||
Reference in New Issue
Block a user