阅读量:2
在Ubuntu上使用Node.js连接数据库,首先需要确保已经安装了Node.js和相应的数据库。以下是连接MySQL和MongoDB数据库的示例。
- 连接MySQL数据库:
步骤1:安装MySQL服务器
sudo apt update
sudo apt install mysql-server
步骤2:安装Node.js MySQL驱动
sudo apt install nodejs npm
npm install mysql
步骤3:创建一个名为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('Successfully connected to the database.');
});
// Your query and other operations go here
connection.end();
步骤4:运行app.js文件
node app.js
- 连接MongoDB数据库:
步骤1:安装MongoDB服务器
sudo apt update
sudo apt install -y mongodb
步骤2:安装Node.js MongoDB驱动
npm install mongodb
步骤3:创建一个名为app.js的文件,并添加以下代码:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://your_username:your_password@localhost:27017/your_database";
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
console.log('Successfully connected to the database.');
const db = client.db('your_database');
// Your query and other operations go here
client.close();
});
步骤4:运行app.js文件
node app.js
请根据实际情况替换your_username、your_password和your_database。这些示例适用于本地数据库连接。如果需要连接到远程数据库,请将localhost替换为远程数据库的IP地址。
以上就是关于“ubuntu上nodejs如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm