插件窝 干货文章 linux node.js怎样连接数据库

linux node.js怎样连接数据库

连接 数据库 const database 815    来源:    2025-05-15

Node.js 连接数据库指南

在 Linux 环境下使用 Node.js 连接数据库有多种方式,具体取决于你要连接的数据库类型。以下是几种常见数据库的连接方法:

1. MySQL 数据库连接

安装 MySQL 驱动

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();

2. PostgreSQL 数据库连接

安装 PostgreSQL 驱动

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();

3. MongoDB 数据库连接

安装 MongoDB 驱动

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);

4. SQLite 数据库连接

安装 SQLite 驱动

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.');
});

5. 使用 ORM 框架 (以 Sequelize 为例)

安装 Sequelize 和对应数据库驱动

# 对于 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();

最佳实践

  1. 使用连接池:对于生产环境,总是使用连接池而不是单个连接
  2. 环境变量管理:不要将数据库凭据硬编码在代码中,使用环境变量或配置管理
  3. 错误处理:始终正确处理数据库错误
  4. 连接关闭:确保在适当的时候关闭数据库连接
  5. 使用 ORM:对于复杂应用,考虑使用 ORM 框架如 Sequelize、TypeORM 或 Mongoose

常见问题解决

  1. 连接被拒绝

    • 检查数据库服务是否运行 (sudo systemctl status mysql 等)
    • 检查防火墙设置
    • 确认数据库用户有远程连接权限(如果需要)
  2. 认证失败

    • 检查用户名和密码
    • 确认用户有访问指定数据库的权限
  3. 连接超时

    • 检查网络连接
    • 增加连接超时设置

希望这些信息能帮助你在 Linux 环境下使用 Node.js 成功连接数据库!