温馨提示×

linux js怎么连接数据库

小樊
48
2026-10-27 21:59:38
栏目: 编程语言

在 Linux 下用 JavaScript(Node.js)连接数据库,常见方式如下,按数据库类型给你示例。


一、前提条件

  1. 已安装 Node.js
node -v
npm -v
  1. 初始化项目
mkdir demo && cd demo
npm init -y

二、连接 MySQL(最常用)

1. 安装依赖

npm install mysql2

2. 示例代码

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'test'
});

connection.connect(err => {
  if (err) {
    console.error('连接失败:', err);
    return;
  }
  console.log('MySQL 连接成功');
});

connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});

connection.end();

三、连接 PostgreSQL

1. 安装依赖

npm install pg

2. 示例代码

const { Client } = require('pg');

const client = new Client({
  host: 'localhost',
  user: 'postgres',
  password: 'password',
  database: 'test',
  port: 5432
});

client.connect()
  .then(() => client.query('SELECT * FROM users'))
  .then(res => console.log(res.rows))
  .catch(err => console.error(err))
  .finally(() => client.end());

四、连接 MongoDB(NoSQL)

1. 安装依赖

npm install mongodb

2. 示例代码

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

async function run() {
  await client.connect();
  const db = client.db('test');
  const col = db.collection('users');
  const data = await col.find({}).toArray();
  console.log(data);
  await client.close();
}

run();

五、使用 ORM(推荐)

  • Sequelize(MySQL / PostgreSQL)
  • Prisma(通用,现代方案)
  • TypeORM

示例(Prisma):

npm install @prisma/client
npx prisma init

六、常见问题

  1. 连不上?
    • 确认数据库在运行
    • 检查防火墙 / 端口
    • 确认用户权限
  2. 远程连接
    host: '192.168.1.100'
    
  3. 生产环境
    • 不要硬编码密码
    • 使用环境变量

如果你告诉我:

  • 用的什么数据库(MySQL / PG / Mongo)
  • 是否在服务器上运行
  • 是否用框架(Express / Nest)

我可以给你更精确的代码。

0 踩