在 Linux 环境下使用 Node.js 连接数据库有多种方式,具体取决于你要连接的数据库类型。以下是几种常见数据库的连接方法:
npm install mysql2
const mysql = require('mysql2');
// 创建连接池(推荐生产环境使用)
const pool = mysql.createPool({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// 使用 Promise 接口
const promisePool = pool.promise();
// 查询示例
async function queryExample() {
try {
const [rows, fields] = await promisePool.query('SELECT * FROM your_table');
console.log(rows);
} catch (err) {
console.error(err);
}
}
queryExample();
npm install pg
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_username',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
async function queryExample() {
try {
const res = await pool.query('SELECT * FROM your_table');
console.log(res.rows);
} catch (err) {
console.error(err);
}
}
queryExample();
npm install mongodb
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('your_database');
const collection = database.collection('your_collection');
// 查询示例
const query = { name: 'John Doe' };
const result = await collection.findOne(query);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
npm install sqlite3
const sqlite3 = require('sqlite3').verbose();
// 打开数据库连接
const db = new sqlite3.Database('./your_database.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the SQLite database.');
});
// 查询示例
db.all('SELECT * FROM your_table', [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row);
});
});
// 关闭连接
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
});
# 对于 MySQL/MariaDB
npm install sequelize mysql2
# 对于 PostgreSQL
npm install sequelize pg pg-hstore
# 对于 SQLite
npm install sequelize sqlite3
const { Sequelize } = require('sequelize');
// 根据数据库类型配置连接
const sequelize = new Sequelize('your_database', 'your_username', 'your_password', {
host: 'localhost',
dialect: 'mysql', // 可以是 'mysql', 'postgres', 'sqlite', 'mariadb', 'mssql'
});
// 测试连接
async function testConnection() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnection();
连接被拒绝:
sudo systemctl status mysql
等)认证失败:
连接超时:
希望这些信息能帮助你在 Linux 环境下使用 Node.js 成功连接数据库!