在CentOS系统中,Node.js可以通过各种数据库驱动程序连接到数据库。以下是一些常见数据库的连接方法:
- 连接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_username、your_password和your_database为实际的MySQL数据库信息。
- 连接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_username、your_password和your_database为实际的PostgreSQL数据库信息。
- 连接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中连接到不同的数据库。根据实际需求,可以编写相应的查询逻辑。
以上就是关于“centos中nodejs如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm