溫馨提示×

ubuntu里nodejs如何連接數據庫

小樊
42
2025-04-01 08:29:39
欄目: 編程語言

在Ubuntu系統中,Node.js可以通過各種數據庫驅動程序連接到數據庫。以下是一些常見數據庫的連接方法:

  1. 連接到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();
});
  1. 連接到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!');
  // 在這里執行數據庫操作
});
  1. 連接到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、passwordmyDatabase替換為您的實際數據庫憑據和名稱。

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