在 Ubuntu 上用 Node.js 连接数据库,一般分三步:安装数据库 → 安装 Node.js 驱动 → 写代码连接。下面按常见数据库给你示例。
sudo apt update
sudo apt install nodejs npm -y
node -v
npm -v
mkdir demo && cd demo
npm init -y
sudo apt install mysql-server -y
sudo mysql_secure_installation
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();
});
sudo apt install postgresql postgresql-contrib -y
sudo -u postgres psql
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));
sudo apt install mongodb -y
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();
const db = client.db('test');
const col = db.collection('users');
await col.insertOne({ name: 'Tom' });
console.log('MongoDB connected');
await client.close();
}
run();
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)如果你告诉我:
我可以直接给你一套完整可运行代码。