在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地址。