在 Debian 系统上,Node.js 连接数据库的一般步骤是:安装数据库 → 安装对应数据库驱动 → 编写 Node.js 代码连接。下面按常见数据库分别说明。
# 使用 apt 安装(版本可能较旧)
sudo apt update
sudo apt install -y nodejs npm
# 查看版本
node -v
npm -v
如需最新版(推荐):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
sudo apt install -y mariadb-server
sudo systemctl start mariadb
sudo mysql_secure_installation
CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
npm init -y
npm install mysql2
const mysql = require('mysql2/promise');
(async () => {
const conn = await mysql.createConnection({
host: 'localhost',
user: 'testuser',
password: 'password',
database: 'testdb'
});
const [rows] = await conn.execute('SELECT NOW() AS now');
console.log(rows);
await conn.end();
})();
sudo apt install -y postgresql
sudo systemctl start postgresql
sudo -u postgres psql
CREATE DATABASE testdb;
CREATE USER testuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE testdb TO testuser;
\q
npm install pg
const { Pool } = require('pg');
const pool = new Pool({
host: 'localhost',
user: 'testuser',
password: 'password',
database: 'testdb',
port: 5432
});
pool.query('SELECT NOW()', (err, res) => {
console.log(res.rows);
pool.end();
});
sudo apt install -y mongodb
sudo systemctl start mongodb
或使用官方 MongoDB 6/7(推荐)
npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
(async () => {
await client.connect();
const db = client.db('testdb');
const col = db.collection('users');
await col.insertOne({ name: 'Tom' });
const data = await col.find().toArray();
console.log(data);
await client.close();
})();
npm install sqlite3
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./test.db');
db.serialize(() => {
db.run('CREATE TABLE IF NOT EXISTS user (id INTEGER, name TEXT)');
db.run('INSERT INTO user VALUES (1, "Tom")');
db.all('SELECT * FROM user', (err, rows) => {
console.log(rows);
});
});
db.close();
sudo systemctl status mariadb
sudo systemctl status postgresql
确保用户允许 localhost 登录,而不是 % 或远程 IP。
✅ 使用 环境变量 管理数据库配置
npm install dotenv
require('dotenv').config();
DB_HOST=localhost
DB_USER=testuser
DB_PASS=password
DB_NAME=testdb
✅ 使用 连接池(生产环境)
✅ 使用 ORM(大型项目)
如果你能告诉我:
我可以给你更精确的配置示例 ✅