使用MySql数据库
安装
bun add mysql2
创建连接
// 导入模块
// const mysql = require('mysql2');
import mysql from 'mysql2'
// 创建连接池,设置连接池的参数
export const getDB = () => {
return mysql.createPool({
host: 'localhost',
user: 'root',
database: 'blog',
password: '123456',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
}).promise()
}
使用express框架
import express from 'express'
import {getDB} from "./utils/db.ts";
const app = express()
const port = 3000
const con = getDB()
app.get('/',(req,res)=> res.send('Hello World!'))
app.get('/posts',async (req,res) => {
try {
const [rows] = await con.query('SELECT * FROM `posts`');
console.log('帖子列表',rows)
res.send(JSON.stringify(rows));
}catch (error:any) {
console.error('报错: ', error);
res.status(500).send('有一个错误');
}
})
app.listen(port,()=>console.log(`app listening on port ${port}!`))
运行结果: Terminal的显示:
浏览器显示结果:
使用Elysia框架
import { Elysia } from "elysia";
import {getDB} from "./utils/db";
//const app = new Elysia().get("/", () => "Hello Elysia").listen(3000);
const app = new Elysia();
const con = getDB()
//获取全部帖子
app.get("/posts",async (ctx) => {
try {
const [rows] = await con.query('SELECT * FROM `posts`');
console.log('帖子列表',rows)
return new Response(JSON.stringify(rows));
}catch (error:any) {
return new Response(error.message, { status: 500 });
}
}).listen(3000)
运行结果: Terminal的显示:
浏览器显示: