在 Debian 上用 Node.js 连接数据库,一般步骤是:安装 Node.js → 安装数据库 → 用 Node 的数据库驱动/ORM 连接。下面按常见数据库分别说。
# 使用 NodeSource(推荐)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v
sudo apt install -y mariadb-server
sudo mysql_secure_installation
CREATE DATABASE testdb;
CREATE USER 'nodeuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'nodeuser'@'localhost';
FLUSH PRIVILEGES;
npm init -y
npm install mysql2
// db.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'nodeuser',
password: 'password',
database: 'testdb'
});
pool.query('SELECT 1 + 1 AS result', (err, rows) => {
if (err) throw err;
console.log(rows);
});
sudo apt install -y postgresql postgresql-contrib
sudo -u postgres psql
CREATE DATABASE testdb;
CREATE USER nodeuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE testdb TO nodeuser;
npm install pg
const { Pool } = require('pg');
const pool = new Pool({
user: 'nodeuser',
host: 'localhost',
database: 'testdb',
password: 'password',
port: 5432
});
pool.query('SELECT NOW()', (err, res) => {
if (err) throw err;
console.log(res.rows);
});
sudo apt install -y mongodb
# 或官方 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('testdb');
const col = db.collection('users');
await col.insertOne({ name: 'Tom' });
console.log(await col.find().toArray());
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, "Tom")');
db.all('SELECT * FROM user', (err, rows) => {
console.log(rows);
});
});
sudo systemctl status mysql127.0.0.1 还是 0.0.0.0bind-address'user'@'%' 用户.env如果你告诉我:
✅ 用的什么数据库
✅ 本地还是远程
✅ Node 版本
我可以直接给你可运行代码。