温馨提示×

ubuntu nodejs如何连数据库

小樊
48
2026-09-22 01:35:14
栏目: 编程语言

在 Ubuntu 上用 Node.js 连接数据库,一般流程是:
安装 Node.js → 安装数据库 → 安装对应数据库驱动 → 写代码连接

下面按常见数据库分别说明(以 MySQL / PostgreSQL / MongoDB 为例)。


一、准备工作(Ubuntu)

1. 安装 Node.js

sudo apt update
sudo apt install -y nodejs npm

检查:

node -v
npm -v

2. 初始化项目

mkdir myapp
cd myapp
npm init -y

二、连接 MySQL(最常用)

1. 安装 MySQL

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

2. 安装 Node.js MySQL 驱动

npm install mysql2

3. 示例代码

const mysql = require('mysql2');

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

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

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

三、连接 PostgreSQL

1. 安装 PostgreSQL

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

2. 安装驱动

npm install pg

3. 示例代码

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

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

client.connect()
  .then(() => console.log('PostgreSQL 连接成功'))
  .then(() => client.end());

四、连接 MongoDB

1. 安装 MongoDB

sudo apt install -y mongodb
sudo systemctl start mongodb

2. 安装驱动

npm install mongodb

3. 示例代码

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

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

async function run() {
  await client.connect();
  console.log('MongoDB 连接成功');
  await client.close();
}
run();

五、常见问题

1. 连接被拒绝

  • 数据库没启动
  • 端口不对
  • 用户权限问题

2. 远程连接

修改数据库配置(如 MySQL 的 bind-address),并开放防火墙。

3. 推荐使用连接池

const pool = mysql.createPool({...});

如果你告诉我:

  • 用的 哪种数据库
  • 是否 远程服务器
  • 是否用 框架(Express / NestJS)

我可以给你更具体的示例。

0