第七章:数据库操作

作者:Administrator 发布时间: 2026-03-13 阅读量:7 评论数:0

第七章:数据库操作

7.1 MySQL数据库

安装与连接

npm install mysql2
// db.js
const mysql = require('mysql2/promise');
​
// 创建连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'myapp',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});
​
module.exports = pool;

CRUD操作

const pool = require('./db');
​
// 查询所有用户
async function getUsers() {
    const [rows] = await pool.execute('SELECT * FROM users');
    return rows;
}
​
// 根据ID查询用户
async function getUserById(id) {
    const [rows] = await pool.execute(
        'SELECT * FROM users WHERE id = ?',
        [id]
    );
    return rows[0];
}
​
// 创建用户
async function createUser(name, email) {
    const [result] = await pool.execute(
        'INSERT INTO users (name, email) VALUES (?, ?)',
        [name, email]
    );
    return result.insertId;
}
​
// 更新用户
async function updateUser(id, name, email) {
    const [result] = await pool.execute(
        'UPDATE users SET name = ?, email = ? WHERE id = ?',
        [name, email, id]
    );
    return result.affectedRows;
}
​
// 删除用户
async function deleteUser(id) {
    const [result] = await pool.execute(
        'DELETE FROM users WHERE id = ?',
        [id]
    );
    return result.affectedRows;
}
​
// 事务处理
async function transferMoney(fromId, toId, amount) {
    const connection = await pool.getConnection();
    
    try {
        await connection.beginTransaction();
        
        // 扣款
        await connection.execute(
            'UPDATE accounts SET balance = balance - ? WHERE id = ?',
            [amount, fromId]
        );
        
        // 收款
        await connection.execute(
            'UPDATE accounts SET balance = balance + ? WHERE id = ?',
            [amount, toId]
        );
        
        await connection.commit();
        return true;
    } catch (err) {
        await connection.rollback();
        throw err;
    } finally {
        connection.release();
    }
}
​
module.exports = {
    getUsers,
    getUserById,
    createUser,
    updateUser,
    deleteUser
};

7.2 MongoDB数据库

安装与连接

npm install mongoose
// db.js
const mongoose = require('mongoose');
​
// 连接数据库
mongoose.connect('mongodb://localhost:27017/myapp', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
​
const db = mongoose.connection;
​
db.on('error', console.error.bind(console, '连接错误:'));
db.once('open', () => {
    console.log('MongoDB连接成功');
});
​
module.exports = mongoose;

定义模型

// models/User.js
const mongoose = require('mongoose');
​
// 定义Schema
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        lowercase: true
    },
    age: {
        type: Number,
        min: 0,
        max: 150
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});
​
// 创建模型
const User = mongoose.model('User', userSchema);
​
module.exports = User;

CRUD操作

const User = require('./models/User');
​
// 创建用户
async function createUser(userData) {
    const user = new User(userData);
    return await user.save();
}
​
// 查询所有用户
async function getUsers() {
    return await User.find();
}
​
// 根据ID查询
async function getUserById(id) {
    return await User.findById(id);
}
​
// 条件查询
async function getUsersByAge(minAge, maxAge) {
    return await User.find({
        age: { $gte: minAge, $lte: maxAge }
    });
}
​
// 更新用户
async function updateUser(id, updateData) {
    return await User.findByIdAndUpdate(id, updateData, { new: true });
}
​
// 删除用户
async function deleteUser(id) {
    return await User.findByIdAndDelete(id);
}
​
// 复杂查询
async function searchUsers(keyword) {
    return await User.find({
        $or: [
            { name: { $regex: keyword, $options: 'i' } },
            { email: { $regex: keyword, $options: 'i' } }
        ]
    });
}
​
module.exports = {
    createUser,
    getUsers,
    getUserById,
    updateUser,
    deleteUser
};

7.3 Redis缓存

安装与连接

npm install redis
// redis.js
const redis = require('redis');

const client = redis.createClient({
    host: 'localhost',
    port: 6379
});

client.on('error', (err) => {
    console.error('Redis错误:', err);
});

module.exports = client;

基本操作

const client = require('./redis');

// 字符串操作
async function stringOperations() {
    // 设置值
    await client.set('key', 'value');
    
    // 设置过期时间(秒)
    await client.setex('session', 3600, 'user123');
    
    // 获取值
    const value = await client.get('key');
    console.log(value);
    
    // 删除
    await client.del('key');
}

// 哈希操作
async function hashOperations() {
    // 设置哈希字段
    await client.hset('user:1', 'name', '张三');
    await client.hset('user:1', 'age', '25');
    
    // 获取单个字段
    const name = await client.hget('user:1', 'name');
    
    // 获取所有字段
    const user = await client.hgetall('user:1');
    console.log(user);
    
    // 删除字段
    await client.hdel('user:1', 'age');
}

// 列表操作
async function listOperations() {
    // 左侧插入
    await client.lpush('queue', 'task1');
    await client.lpush('queue', 'task2');
    
    // 右侧插入
    await client.rpush('queue', 'task3');
    
    // 获取列表
    const tasks = await client.lrange('queue', 0, -1);
    console.log(tasks);
    
    // 左侧弹出
    const task = await client.lpop('queue');
    console.log(task);
}

// 集合操作
async function setOperations() {
    // 添加成员
    await client.sadd('tags', 'nodejs');
    await client.sadd('tags', 'javascript');
    
    // 获取所有成员
    const tags = await client.smembers('tags');
    console.log(tags);
    
    // 检查成员是否存在
    const exists = await client.sismember('tags', 'nodejs');
    console.log(exists);
    
    // 删除成员
    await client.srem('tags', 'nodejs');
}

module.exports = {
    stringOperations,
    hashOperations,
    listOperations,
    setOperations
};

7.4 Sequelize ORM

安装与配置

npm install sequelize mysql2
// db.js
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('myapp', 'root', 'password', {
    host: 'localhost',
    dialect: 'mysql',
    logging: false
});

module.exports = sequelize;

定义模型

// models/User.js
const { DataTypes } = require('sequelize');
const sequelize = require('../db');

const User = sequelize.define('User', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false
    },
    age: {
        type: DataTypes.INTEGER
    }
}, {
    tableName: 'users',
    timestamps: true
});

module.exports = User;

使用模型

const User = require('./models/User');

// 同步模型
async function sync() {
    await User.sync({ force: true });  // 删除并重建表
    console.log('模型同步完成');
}

// CRUD操作
async function crud() {
    // 创建
    const user = await User.create({
        name: '张三',
        email: 'zhangsan@example.com',
        age: 25
    });
    
    // 查询所有
    const users = await User.findAll();
    
    // 条件查询
    const adults = await User.findAll({
        where: {
            age: { [Op.gte]: 18 }
        }
    });
    
    // 更新
    await User.update(
        { age: 26 },
        { where: { id: 1 } }
    );
    
    // 删除
    await User.destroy({
        where: { id: 1 }
    });
}

module.exports = { sync, crud };

评论