温馨提示×

centos nodejs如何接数据库

小樊
49
2026-09-14 23:26:50
栏目: 编程语言

CentOS 上使用 Node.js 连接数据库,一般流程是:安装 Node.js → 安装数据库驱动 → 写连接代码 → 运行测试。下面以常见数据库为例说明。


一、前提:安装 Node.js(CentOS)

1. 使用 NodeSource 安装(推荐)

curl -sL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs

验证:

node -v
npm -v

二、连接 MySQL(最常见)

1. 安装 MySQL 驱动

npm init -y
npm install mysql2

2. 示例代码(mysql2)

const mysql = require('mysql2');

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

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();
});

运行:

node index.js

三、连接 PostgreSQL

1. 安装驱动

npm install pg

2. 示例代码

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

const client = new Client({
  host: 'localhost',
  user: 'postgres',
  password: 'yourpassword',
  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));

四、连接 MongoDB

1. 安装驱动

npm install mongodb

2. 示例代码

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

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

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

run();

五、常见问题(CentOS 特有)

1. 数据库未启动

# MySQL
systemctl start mysqld

# PostgreSQL
systemctl start postgresql

# MongoDB
systemctl start mongod

2. 防火墙端口未开放

firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --reload

3. 只允许本地连接

检查数据库配置(如 MySQL 的 bind-address)。


六、生产建议

  • 使用 连接池(mysql2 / pg 都支持)
  • 使用 环境变量 存储数据库密码
  • 使用 ORM(如 Sequelize、Prisma、TypeORM)

如果你能告诉我:

  • 用的是哪种数据库(MySQL / PostgreSQL / MongoDB)
  • CentOS 版本
  • 是否本地或远程数据库

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

0