文章 文章 posts

Node.js 操作 MySQL / PostgreSQL

在 Web 开发中,数据库是必不可少的组件。Node.js 支持多种数据库,其中 MySQL 和 PostgreSQL 是最常用的关系型数据库。本文将演示如何用 Node.js 操作 MySQL 和 PostgreSQL。

1. 安装依赖

MySQL

bash
npm install mysql2

`

PostgreSQL

bash
npm install pg

2. 连接数据库

2.1 连接 MySQL

js
const mysql = require('mysql2/promise');

async function main() {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'test_db'
  });

  console.log('MySQL 连接成功!');

  await connection.end();
}

main();

2.2 连接 PostgreSQL

js
const { Client } = require('pg');

async function main() {
  const client = new Client({
    host: 'localhost',
    user: 'postgres',
    password: 'your_password',
    database: 'test_db',
    port: 5432
  });

  await client.connect();
  console.log('PostgreSQL 连接成功!');

  await client.end();
}

main();

3. 执行查询

3.1 MySQL 查询

js
const [rows] = await connection.execute('SELECT * FROM users');
console.log(rows);

3.2 PostgreSQL 查询

js
const res = await client.query('SELECT * FROM users');
console.log(res.rows);

4. 插入数据

4.1 MySQL 插入

js
await connection.execute(
  'INSERT INTO users(name, email) VALUES(?, ?)',
  ['Alice', 'alice@example.com']
);
console.log('插入成功!');

4.2 PostgreSQL 插入

js
await client.query(
  'INSERT INTO users(name, email) VALUES($1, $2)',
  ['Alice', 'alice@example.com']
);
console.log('插入成功!');

5. 总结

  • 使用 Node.js 操作数据库主要依赖官方或社区提供的驱动 mysql2、pg。
  • 建议使用 async/await,避免回调地狱。
  • 查询语句中的占位符可以防止 SQL 注入。
  • MySQL 和 PostgreSQL 的语法略有差异,但操作逻辑类似:连接 → 查询 → 插入/更新/删除 → 关闭连接。