温馨提示×

ubuntu nodejs怎么连接数据库

小樊
42
2026-09-16 00:12:39
栏目: 编程语言

在 Ubuntu 上用 Node.js 连接数据库,一般分三步:安装数据库 → 安装 Node.js 驱动 → 写代码连接。下面按常见数据库给你示例。


一、准备工作(Ubuntu)

1. 安装 Node.js

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

2. 初始化项目

mkdir demo && cd demo
npm init -y

二、连接常见数据库示例

✅ 1. MySQL / MariaDB

安装 MySQL

sudo apt install mysql-server -y
sudo mysql_secure_installation

安装 Node 驱动

npm install mysql2

示例代码

const mysql = require('mysql2');

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

connection.connect(err => {
  if (err) throw err;
  console.log('MySQL connected');
});

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

✅ 2. PostgreSQL

安装 PostgreSQL

sudo apt install postgresql postgresql-contrib -y
sudo -u postgres psql

安装 Node 驱动

npm install pg

示例代码

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

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

client.connect()
  .then(() => client.query('SELECT NOW()'))
  .then(res => {
    console.log(res.rows);
    return client.end();
  })
  .catch(err => console.error(err));

✅ 3. MongoDB

安装 MongoDB

sudo apt install mongodb -y
sudo systemctl start mongodb

安装 Node 驱动

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('test');
  const col = db.collection('users');
  await col.insertOne({ name: 'Tom' });
  console.log('MongoDB connected');
  await client.close();
}

run();

✅ 4. SQLite(轻量,无需服务)

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

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

三、常见问题

❓ 连接被拒绝

  • 数据库是否启动
sudo systemctl status mysql
  • 是否允许本地连接
  • 用户名/密码是否正确

❓ 远程连接

  • 修改配置文件(bind-address
  • 开放防火墙端口

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

  • 使用 连接池
  • 使用 环境变量 存密码
  • 使用 ORM(如 Sequelize / Prisma / TypeORM)

如果你告诉我:

  • 用的是 哪种数据库
  • 是否 远程连接
  • 是否用 Express / NestJS

我可以直接给你一套完整可运行代码。

0