温馨提示×

ubuntu nodejs怎么连数据库

小樊
41
2026-09-25 03:32:42
栏目: 编程语言

在 Ubuntu 上用 Node.js 连接数据库,通常分为 安装数据库 → 安装 Node.js → 安装对应数据库驱动 → 写代码连接 几个步骤。下面以常见数据库为例说明。


一、环境准备

1. 安装 Node.js(Ubuntu)

sudo apt update
sudo apt install nodejs npm -y
node -v
npm -v

2. 初始化项目

mkdir node-db-demo
cd node-db-demo
npm init -y

二、连接 MySQL(最常见)

1. 安装 MySQL

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

2. 创建数据库和用户

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

3. 安装 Node.js MySQL 驱动

npm install mysql2

4. 示例代码(mysql2)

const mysql = require('mysql2');

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

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

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

connection.end();

三、连接 PostgreSQL

1. 安装 PostgreSQL

sudo apt install postgresql postgresql-contrib -y
sudo systemctl start postgresql

2. 创建用户和数据库

sudo -u postgres psql
CREATE DATABASE testdb;
CREATE USER nodeuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE testdb TO nodeuser;

3. 安装 pg 驱动

npm install pg

4. 示例代码

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

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

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

四、连接 MongoDB

1. 安装 MongoDB

sudo apt install mongodb -y
sudo systemctl start mongodb

2. 安装 mongoose

npm install mongoose

3. 示例代码

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

mongoose.connection.on('connected', () => {
  console.log('MongoDB 连接成功');
});

五、常见问题

  • 连接被拒绝

    • 数据库是否启动
    • 是否允许 localhost 连接
    • 防火墙 / bind-address 配置
  • 生产环境建议

    • 使用连接池(mysql2 / pg Pool)
    • 密码使用环境变量(dotenv)
    • 不要硬编码密码

如果你告诉我:

  • 用的是 哪种数据库(MySQL / PostgreSQL / MongoDB / SQLite)
  • 是 本地还是远程服务器
  • 是否 Docker 环境

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

0 踩