
本文介绍如何在Linux系统中使用Node.js连接不同类型的数据库。 请确保已安装Node.js及相关数据库驱动程序。
一、连接MySQL数据库
<code class="bash">npm install mysql</code>
db.js):<code class="javascript">const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: '你的用户名',
password: '你的密码',
database: '你的数据库名'
});
connection.connect(err => {
if (err) {
console.error('数据库连接失败:', err);
return;
}
console.log('MySQL数据库连接成功!');
});
// 在此处添加你的数据库操作代码
connection.end();</code>请替换你的用户名、你的密码和你的数据库名为你的实际数据库凭据。
二、连接PostgreSQL数据库
<code class="bash">npm install pg</code>
db.js):<code class="javascript">const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: '你的用户名',
password: '你的密码',
database: '你的数据库名',
port: 5432 // PostgreSQL默认端口
});
client.connect(err => {
if (err) {
console.error('数据库连接失败:', err);
return;
}
console.log('PostgreSQL数据库连接成功!');
});
// 在此处添加你的数据库操作代码
client.end();</code>同样,请替换占位符为你的实际数据库信息。
三、连接MongoDB数据库
<code class="bash">npm install mongodb</code>
db.js):<code class="javascript">const { MongoClient } = require('mongodb');
const uri = 'mongodb://你的用户名:你的密码@localhost:27017/你的数据库名';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
if (err) {
console.error('数据库连接失败:', err);
return;
}
console.log('MongoDB数据库连接成功!');
// 在此处添加你的数据库操作代码
client.close();
});</code>请将占位符替换为你的MongoDB连接字符串。
以上示例展示了在Linux环境下使用Node.js连接MySQL、PostgreSQL和MongoDB数据库的基本方法。 你可以根据实际情况调整代码并连接其他类型的数据库。 记住替换示例中的占位符为你的实际数据库信息。
以上就是linux node.js怎样连接数据库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号