1. 字符串函数
-- CONCAT:拼接(≈ + 或模板字符串)
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
大约 4 分钟
-- CONCAT:拼接(≈ + 或模板字符串)
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
-- 没有索引时,查询会逐行扫描(≈ for 循环找)
SELECT * FROM users WHERE name = '小明';
-- 如果 users 有 100 万行,就要比较 100 万次
| 场景 | 以前(纯前端) | 加上数据库 |
|---|---|---|
| 数据存储 | LocalStorage / JSON 文件 | MySQL 持久化 |
| 接口数据 | 写死 mock 数据 | 真实 CRUD |
| 全栈能力 | 调后端接口 | 自己写接口+查数据 |
| 面试 | 只有前端知识 | 全栈竞争力 |
<!-- pom.xml -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
// 前端:分开存储关联数据
const users = [
{ id: 1, name: '小明' },
{ id: 2, name: '小红' },
];
const orders = [
{ id: 101, user_id: 1, amount: 100, product: '键盘' },
{ id: 102, user_id: 2, amount: 200, product: '鼠标' },
{ id: 103, user_id: 1, amount: 150, product: '显示器' },
];
// 前端关联方式:find 串联
function getUserOrders(userId) {
return orders.filter(o => o.user_id === userId);
}
// 要显示"用户名 + 订单信息":
const result = orders.map(order => {
const user = users.find(u => u.id === order.user_id);
return {
用户名: user?.name,
商品: order.product,
金额: order.amount,
};
});
npm install mysql2
const mysql = require('mysql2/promise'); // 使用 Promise 版本(推荐)
// 连接配置(类似前端请求的 baseURL + 鉴权)
const pool = mysql.createPool({
host: 'localhost', // 数据库主机
port: 3306, // MySQL 默认端口
user: 'root', // 用户名
password: '123456', // 密码
database: 'my_app', // 数据库名
waitForConnections: true,
connectionLimit: 10, // 连接池大小
queueLimit: 0,
});
// 测试连接
async function testConnection() {
try {
const connection = await pool.getConnection();
console.log('数据库连接成功 ✅');
connection.release();
} catch (err) {
console.error('数据库连接失败 ❌', err);
}
}
// 前端:统计订单数据
const orders = [
{ id: 1, customer: '小明', amount: 100, status: 'completed' },
{ id: 2, customer: '小红', amount: 200, status: 'completed' },
{ id: 3, customer: '小刚', amount: 150, status: 'pending' },
];
const total = orders.reduce((s, o) => s + o.amount, 0); // 总金额
const count = orders.length; // 订单数
const avg = total / count; // 平均金额
const max = Math.max(...orders.map(o => o.amount)); // 最大金额
const min = Math.min(...orders.map(o => o.amount)); // 最小金额
// 前端:JS 数组存数据
const users = [
{ id: 1, name: "小明", age: 25, city: "北京" },
{ id: 2, name: "小红", age: 23, city: "上海" },
{ id: 3, name: "小刚", age: 28, city: "北京" },
];
INT -- 整数(-21亿~21亿)≈ JS Number 整数部分
BIGINT -- 大整数 ≈ BigInt
DECIMAL(10,2) -- 精确小数(金额用!)≈ toFixed(2) 但更精确
FLOAT / DOUBLE -- 浮点数(精度有损失)
TINYINT -- 小整数(0~255),常用作布尔值
// 前端:还记得请求缓存吗?
const cache = new Map();
async function fetchUser(id) {
if (cache.has(id)) {
return cache.get(id); // 缓存命中
}
const data = await api.getUser(id); // 查数据库
cache.set(id, data); // 写入缓存
return data;
}