在 Ubuntu 上用 Node.js 连接数据库,一般流程是:
安装 Node.js → 安装数据库 → 安装对应数据库驱动 → 写代码连接
下面按常见数据库分别说明(以 MySQL / PostgreSQL / MongoDB 为例)。
sudo apt update
sudo apt install -y nodejs npm
检查:
node -v
npm -v
mkdir myapp
cd myapp
npm init -y
sudo apt install -y mysql-server
sudo systemctl start mysql
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) {
console.error('连接失败:', err);
return;
}
console.log('MySQL 连接成功');
});
connection.query('SELECT 1 + 1 AS result', (err, rows) => {
console.log(rows);
connection.end();
});
sudo apt install -y postgresql postgresql-contrib
sudo systemctl start postgresql
npm install pg
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());
sudo apt install -y mongodb
sudo systemctl start mongodb
npm install mongodb
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();
修改数据库配置(如 MySQL 的 bind-address),并开放防火墙。
const pool = mysql.createPool({...});
如果你告诉我:
我可以给你更具体的示例。