centos

centos中nodejs如何连接数据库

小樊
44
2025-05-27 01:03:58
栏目: 编程语言

在CentOS系统中,Node.js可以通过各种数据库驱动程序连接到数据库。以下是一些常见数据库的连接方法:

  1. 连接MySQL数据库:

首先,确保已经安装了MySQL数据库。然后,使用npm安装mysql模块:

npm install mysql

接下来,创建一个名为app.js的文件,并添加以下代码:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

connection.connect(error => {
  if (error) throw error;
  console.log('Connected to the MySQL database.');
});

// Your query logic here

connection.end();

替换your_usernameyour_passwordyour_database为实际的MySQL数据库信息。

  1. 连接PostgreSQL数据库:

首先,确保已经安装了PostgreSQL数据库。然后,使用npm安装pg模块:

npm install pg

接下来,创建一个名为app.js的文件,并添加以下代码:

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

const pool = new Pool({
  user: 'your_username',
  host: 'localhost',
  database: 'your_database',
  password: 'your_password',
  port: 5432
});

pool.connect(error => {
  if (error) throw error;
  console.log('Connected to the PostgreSQL database.');
});

// Your query logic here

pool.end();

替换your_usernameyour_passwordyour_database为实际的PostgreSQL数据库信息。

  1. 连接MongoDB数据库:

首先,确保已经安装了MongoDB数据库。然后,使用npm安装mongoose模块:

npm install mongoose

接下来,创建一个名为app.js的文件,并添加以下代码:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/your_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', error => console.error(error));
db.once('open', () => console.log('Connected to the MongoDB database.'));

// Your schema and model definitions here

// Your query logic here

替换your_database为实际的MongoDB数据库信息。

这些示例展示了如何在Node.js中连接到不同的数据库。根据实际需求,可以编写相应的查询逻辑。

0
看了该问题的人还看了