# koa **Repository Path**: shunxuan/koa ## Basic Information - **Project Name**: koa - **Description**: 连接mysq - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-27 - **Last Updated**: 2026-03-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: koa2, MySQL ## README # 连接mysq ```js const mysql = require('mysql2/promise'); const pool = mysql.createPool({ host: 'localhost', user: 'root', password: '123456', database: 'test', port: 3306, waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); // 监听连接事件 pool.on('connection', (connection) => { console.log('MySQL: 新连接建立,连接ID:', connection.threadId); }); pool.on('acquire', (connection) => { console.log('MySQL: 连接被获取,连接ID:', connection.threadId); }); pool.on('release', (connection) => { console.log('MySQL: 连接被释放,连接ID:', connection.threadId); }); pool.on('enqueue', () => { console.log('MySQL: 连接请求进入等待队列'); }); // 测试连接函数 async function testConnection() { let connection; try { connection = await pool.getConnection(); console.log('✅ MySQL 连接成功!'); // 获取数据库信息 const [rows] = await connection.query('SELECT VERSION() as version'); console.log(`📊 MySQL 版本: ${rows[0].version}`); return true; } catch (error) { console.error('❌ MySQL 连接失败:', error.message); return false; } finally { if (connection) connection.release(); } } testConnection() module.exports = pool; ``` # router ```js const router = require('koa-router')() const userController = require('../controllers/UserController'); router.prefix('/users') router.get('/', userController.getAllUsers); router.get('/:id', userController.getUserById); router.post('/', userController.createUser); module.exports = router ``` # controller ```js const UserModel = require('../models/UserModel'); class UserController { // 获取所有用户 async getAllUsers(ctx) { try { const users = await UserModel.findAll(); ctx.body = { code: 200, data: users, message: '查询成功' }; } catch (error) { ctx.body = { code: 500, message: '服务器错误', error: error.message }; } } // 获取单个用户 async getUserById(ctx) { const { id } = ctx.params; try { const user = await UserModel.findById(id); if (user) { ctx.body = { code: 200, data: user, message: '查询成功' }; } else { ctx.body = { code: 404, message: '用户不存在' }; } } catch (error) { ctx.body = { code: 500, message: '服务器错误' }; } } // 创建用户 async createUser(ctx) { const userData = ctx.request.body; try { const newUser = await UserModel.create(userData); ctx.status = 201; ctx.body = { code: 201, data: newUser, message: '创建成功' }; } catch (error) { ctx.body = { code: 500, message: '创建失败', error: error.message }; } } } module.exports = new UserController(); ``` # model ```js const pool = require('../config/db'); class UserModel { // 查询所有用户 static async findAll() { const [rows] = await pool.query('SELECT * FROM users'); return rows; } // 根据ID查询用户 static async findById(id) { const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]); return rows[0]; } // 创建用户 static async create(userData) { const { name, email } = userData; const [result] = await pool.query( 'INSERT INTO users (name, email) VALUES (?, ?)', [name, email] ); return { id: result.insertId, ...userData }; } // 更新用户 static async update(id, userData) { const { name, email } = userData; const [result] = await pool.query( 'UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id] ); return result.affectedRows > 0; } // 删除用户 static async delete(id) { const [result] = await pool.query('DELETE FROM users WHERE id = ?', [id]); return result.affectedRows > 0; } } module.exports = UserModel; ```