温馨提示×

debian nodejs如何连数据库

小樊
37
2026-09-14 11:29:24
栏目: 编程语言

在 Debian 上用 Node.js 连接数据库,步骤大致是:安装 Node.js → 安装数据库驱动 → 写代码连接 → 运行测试。下面按常见数据库分别说明。


一、准备 Node.js(Debian)

1. 安装 Node.js

sudo apt update
sudo apt install -y nodejs npm

查看版本:

node -v
npm -v

如需新版本,可用 nodesource 源安装。


二、连接常见数据库示例

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 { Client } = require('pg');

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

client.connect()
  .then(() => {
    console.log('PostgreSQL 连接成功');
    return client.query('SELECT 1+1 AS result');
  })
  .then(res => {
    console.log(res.rows);
    return client.end();
  })
  .catch(err => console.error(err));

3️⃣ MongoDB

安装驱动

npm install mongodb

示例代码

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

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

async function run() {
  try {
    await client.connect();
    console.log('MongoDB 连接成功');
    const db = client.db('testdb');
    const col = db.collection('users');
    console.log(await col.find({}).toArray());
  } finally {
    await client.close();
  }
}

run().catch(console.error);

4️⃣ SQLite(轻量,无需服务)

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

const db = new sqlite3.Database(':memory:');
db.serialize(() => {
  db.run('CREATE TABLE test (id INT)');
  db.run('INSERT INTO test VALUES (1)');
  db.all('SELECT * FROM test', (err, rows) => {
    console.log(rows);
  });
});

三、常见问题(Debian)

1. 数据库未启动

sudo systemctl status mysql
sudo systemctl start mysql

2. 防火墙 / 端口

  • 本地:localhost
  • 远程:确保端口开放(3306 / 5432 / 27017)

3. 权限问题

  • MySQL:用户需有远程或本地访问权限
  • PostgreSQL:pg_hba.conf 配置

四、推荐做法(生产环境)

  • 使用 连接池
  • 密码使用环境变量
  • 使用 dotenv
  • 使用 ORM(如 sequelizeprismatypeorm

如果你能告诉我:

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

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

0