在Ubuntu上使用Node.js連接數據庫,首先需要確保已經安裝了Node.js和相應的數據庫。以下是連接MySQL和MongoDB數據庫的示例。
步驟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
步驟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地址。