溫馨提示×

ubuntu上nodejs如何連接數據庫

小樊
56
2025-05-07 12:46:05
欄目: 編程語言

在Ubuntu上使用Node.js連接數據庫,首先需要確保已經安裝了Node.js和相應的數據庫。以下是連接MySQL和MongoDB數據庫的示例。

  1. 連接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
  1. 連接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_passwordyour_database。這些示例適用于本地數據庫連接。如果需要連接到遠程數據庫,請將localhost替換為遠程數據庫的IP地址。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女