温馨提示×

Debian Nodejs如何连接数据库

小樊
40
2026-07-01 19:38:07
栏目: 编程语言

在 Debian 系统上,Node.js 连接数据库的一般步骤是:安装数据库 → 安装对应数据库驱动 → 编写 Node.js 代码连接。下面按常见数据库分别说明。


一、环境准备

1. 安装 Node.js(Debian)

# 使用 apt 安装(版本可能较旧)
sudo apt update
sudo apt install -y nodejs npm

# 查看版本
node -v
npm -v

如需最新版(推荐):

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

二、连接常见数据库


✅ MySQL / MariaDB

1. 安装 MySQL(如未安装)

sudo apt install -y mariadb-server
sudo systemctl start mariadb
sudo mysql_secure_installation

2. 创建数据库和用户

CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;

3. 安装 Node.js MySQL 驱动

npm init -y
npm install mysql2

4. 示例代码(mysql2)

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

(async () => {
  const conn = await mysql.createConnection({
    host: 'localhost',
    user: 'testuser',
    password: 'password',
    database: 'testdb'
  });

  const [rows] = await conn.execute('SELECT NOW() AS now');
  console.log(rows);

  await conn.end();
})();

✅ PostgreSQL

1. 安装 PostgreSQL

sudo apt install -y postgresql
sudo systemctl start postgresql

2. 创建数据库和用户

sudo -u postgres psql

CREATE DATABASE testdb;
CREATE USER testuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE testdb TO testuser;
\q

3. 安装 PostgreSQL 驱动

npm install pg

4. 示例代码

const { Pool } = require('pg');

const pool = new Pool({
  host: 'localhost',
  user: 'testuser',
  password: 'password',
  database: 'testdb',
  port: 5432
});

pool.query('SELECT NOW()', (err, res) => {
  console.log(res.rows);
  pool.end();
});

✅ MongoDB

1. 安装 MongoDB(Debian)

sudo apt install -y mongodb
sudo systemctl start mongodb

或使用官方 MongoDB 6/7(推荐)

2. 安装 Node.js MongoDB 驱动

npm install mongodb

3. 示例代码

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

(async () => {
  await client.connect();
  const db = client.db('testdb');
  const col = db.collection('users');

  await col.insertOne({ name: 'Tom' });
  const data = await col.find().toArray();
  console.log(data);

  await client.close();
})();

✅ SQLite(无需安装数据库服务,适合小型项目)

npm install sqlite3
const sqlite3 = require('sqlite3').verbose();

const db = new sqlite3.Database('./test.db');

db.serialize(() => {
  db.run('CREATE TABLE IF NOT EXISTS user (id INTEGER, name TEXT)');
  db.run('INSERT INTO user VALUES (1, "Tom")');
  db.all('SELECT * FROM user', (err, rows) => {
    console.log(rows);
  });
});

db.close();

三、常见问题排查

1. 连接被拒绝

  • 数据库服务是否启动?
sudo systemctl status mariadb
sudo systemctl status postgresql

2. 端口问题

  • MySQL:3306
  • PostgreSQL:5432
  • MongoDB:27017

3. 权限问题

确保用户允许 localhost 登录,而不是 % 或远程 IP。


四、建议的最佳实践

✅ 使用 环境变量 管理数据库配置

npm install dotenv
require('dotenv').config();
DB_HOST=localhost
DB_USER=testuser
DB_PASS=password
DB_NAME=testdb

✅ 使用 连接池(生产环境)

✅ 使用 ORM(大型项目)

  • MySQL → Sequelize / TypeORM
  • PostgreSQL → Prisma / TypeORM
  • MongoDB → Mongoose

如果你能告诉我:

  • 使用的是 哪种数据库
  • 是否 本地 / 远程
  • 是否 生产环境

我可以给你更精确的配置示例 ✅

0