阅读量:3
在Ubuntu系统中,Node.js可以通过各种数据库驱动程序连接到数据库。以下是一些常见数据库的连接方法:
- 连接到MongoDB:
首先,安装MongoDB驱动程序:
npm install mongodb
然后,使用以下代码连接到MongoDB数据库:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://username:password@localhost:27017/myDatabase";
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db("myDatabase");
// 在这里执行数据库操作
client.close();
});
- 连接到MySQL:
首先,安装MySQL驱动程序:
npm install mysql
然后,使用以下代码连接到MySQL数据库:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'myDatabase'
});
connection.connect(err => {
if (err) throw err;
console.log('Connected to the database!');
// 在这里执行数据库操作
});
- 连接到PostgreSQL:
首先,安装PostgreSQL驱动程序:
npm install pg
然后,使用以下代码连接到PostgreSQL数据库:
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'username',
password: 'password',
database: 'myDatabase'
});
client.connect(err => {
if (err) throw err;
console.log('Connected to the database!');
// 在这里执行数据库操作
});
请根据您使用的数据库类型选择相应的驱动程序,并确保将示例代码中的username、password和myDatabase替换为您的实际数据库凭据和名称。
以上就是关于“ubuntu里nodejs如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm