在JavaScript中操作数据库简介
现代JavaScript网络开发离不开与数据库的交互。Node.js为操作关系型(SQL)和文档型(NoSQL)数据库提供了强大工具。本文将详细介绍如何在JavaScript生态系统中连接并执行两个最流行的数据库管理系统的基本操作:PostgreSQL和MongoDB。
您将学习如何安装驱动程序、配置连接、执行CRUD操作(创建、读取、更新、删除),以及如何为您的项目在SQL和NoSQL之间做出正确选择。
环境设置
要运行示例,您需要Node.js(版本18+)和npm包管理器。确保数据库在本地运行或可通过远程访问。
1. 在Node.js中操作PostgreSQL
PostgreSQL是一款强大的开源关系型数据库。要在Node.js中操作它,我们将使用pg库——官方客户端。
安装与连接
npm install pg让我们创建一个db.js文件来配置连接池:
const { Pool } = require('pg');
const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'mydb', password: 'secret', port: 5432,});
module.exports = pool;PostgreSQL的CRUD操作
让我们看看对users表的基本查询:
创建表(CREATE)
const createTable = async () => { const query = ` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, age INTEGER, created_at TIMESTAMP DEFAULT NOW() ); `; await pool.query(query); console.log('表 users 已创建');};插入数据(INSERT)
const addUser = async (name, email, age) => { const text = 'INSERT INTO users(name, email, age) VALUES($1, $2, $3) RETURNING *'; const values = [name, email, age]; const res = await pool.query(text, values); console.log('用户已添加:', res.rows[0]); return res.rows[0];};
// 使用示例addUser('Ivan Petrov', 'ivan@example.com', 30);读取数据(SELECT)
const getUsers = async (ageLimit) => { const res = await pool.query( 'SELECT * FROM users WHERE age > $1 ORDER BY created_at DESC', [ageLimit] ); return res.rows;};
// 获取年龄大于25岁的用户getUsers(25).then(users => console.log(users));更新与删除(UPDATE / DELETE)
const updateUser = async (id, newName) => { const res = await pool.query( 'UPDATE users SET name = $1 WHERE id = $2 RETURNING *', [newName, id] ); return res.rows[0];};
const deleteUser = async (id) => { await pool.query('DELETE FROM users WHERE id = $1', [id]); console.log(`用户 id 为 ${id} 已被删除`);};重要提示:始终使用参数化查询($1, $2)以防止SQL注入攻击。
2. 在Node.js中操作MongoDB
MongoDB是最流行的NoSQL数据库,以JSON文档格式存储数据。我们将使用官方mongodb驱动程序或流行的ODM库mongoose来操作它。
安装与连接(使用mongoose)
npm install mongooseconst mongoose = require('mongoose');
const connectDB = async () => { try { await mongoose.connect('mongodb://localhost:27017/mydb'); console.log('MongoDB 已连接'); } catch (error) { console.error('连接错误:', error); }};
connectDB();