在 CentOS 上使用 Node.js 连接数据库,一般流程是:安装 Node.js → 安装数据库驱动 → 写连接代码 → 运行测试。下面以常见数据库为例说明。
curl -sL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs
验证:
node -v
npm -v
npm init -y
npm install 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
npm install pg
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));
npm install mongodb
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();
# MySQL
systemctl start mysqld
# PostgreSQL
systemctl start postgresql
# MongoDB
systemctl start mongod
firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --reload
检查数据库配置(如 MySQL 的 bind-address)。
如果你能告诉我:
我可以给你更精确的配置示例。