溫馨提示×

Ubuntu上Node.js如何集成數據庫

小樊
45
2025-07-03 17:45:58
欄目: 編程語言

在Ubuntu上集成Node.js與數據庫,您可以選擇多種數據庫,例如MySQL、PostgreSQL、MongoDB等。以下是針對幾種常見數據庫的集成步驟:

1. MySQL

安裝MySQL服務器

sudo apt update
sudo apt install mysql-server

安裝Node.js MySQL驅動

npm install mysql

示例代碼

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to the MySQL server.');
});

connection.query('SELECT * FROM your_table', (err, results, fields) => {
  if (err) throw err;
  console.log(results);
});

connection.end();

2. PostgreSQL

安裝PostgreSQL服務器

sudo apt update
sudo apt install postgresql postgresql-contrib

安裝Node.js PostgreSQL驅動

npm install pg

示例代碼

const { Pool } = require('pg');

const pool = new Pool({
  user: 'your_username',
  host: 'localhost',
  database: 'your_database',
  password: 'your_password',
  port: 5432,
});

pool.query('SELECT * FROM your_table', (err, res) => {
  if (err) throw err;
  console.log(res.rows);
});

3. MongoDB

安裝MongoDB服務器

sudo apt update
sudo apt install -y mongodb

啟動MongoDB服務

sudo systemctl start mongod

安裝Node.js MongoDB驅動

npm install mongodb

示例代碼

const { MongoClient } = require('mongodb');

async function main() {
  const uri = "mongodb://localhost:27017";
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const database = client.db('your_database');
    const collection = database.collection('your_collection');

    const query = { name: 'your_name' };
    const result = await collection.findOne(query);
    console.log(result);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

總結

以上步驟展示了如何在Ubuntu上集成Node.js與MySQL、PostgreSQL和MongoDB。您可以根據需要選擇合適的數據庫,并按照相應的步驟進行安裝和配置。確保在運行Node.js應用程序之前,數據庫服務器已經啟動并運行。

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