温馨提示×

debian nodejs怎样连接数据库

小樊
45
2026-09-07 16:20:51
栏目: 编程语言

在 Debian 上用 Node.js 连接数据库,通常分为 安装 Node.js → 安装数据库驱动 → 编写连接代码 三步。下面以常见数据库为例说明。


一、在 Debian 上准备 Node.js

1. 安装 Node.js(推荐用 NodeSource)

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

检查:

node -v
npm -v

二、连接常见数据库示例

✅ 1. MySQL / MariaDB

安装驱动

npm init -y
npm install mysql2

示例代码(mysql2)

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'testdb'
});

connection.connect(err => {
  if (err) {
    console.error('连接失败:', err);
    return;
  }
  console.log('MySQL 连接成功');
});

connection.query('SELECT 1 + 1 AS result', (err, rows) => {
  if (err) throw err;
  console.log(rows);
  connection.end();
});

✅ 2. PostgreSQL

安装驱动

npm install pg

示例代码

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

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

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

✅ 3. MongoDB

安装驱动

npm install mongodb

示例代码

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

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

async function run() {
  await client.connect();
  const db = client.db('testdb');
  const col = db.collection('users');
  const data = await col.find({}).toArray();
  console.log(data);
  await client.close();
}

run();

✅ 4. 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 PRIMARY KEY, name TEXT)');
  db.get('SELECT 1 AS val', (err, row) => {
    console.log(row);
  });
});
db.close();

三、Debian 上数据库本身也要安装

例如 MySQL:

sudo apt install mariadb-server
sudo mysql_secure_installation

PostgreSQL:

sudo apt install postgresql

MongoDB(需加官方源):

# 参考 MongoDB 官方 Debian 安装文档

四、常见问题

1. 连接被拒绝

  • 数据库是否启动
  • 是否允许远程/本地连接
  • 防火墙(ufw / iptables)

2. 生产建议

  • 使用连接池(mysql2 / pg Pool)
  • 密码不要写死在代码里(用 .env + dotenv
  • 使用 ORM(Sequelize / Prisma / TypeORM)

如果你告诉我:

  • 用哪种数据库(MySQL / PG / Mongo)
  • Debian 版本
  • 是否是远程服务器

我可以直接给你一份可运行的最小示例 + 配置说明

0