首頁  >  文章  >  web前端  >  nodejs怎麼連接資料庫

nodejs怎麼連接資料庫

下次还敢
下次还敢原創
2024-04-21 05:07:11730瀏覽

在 Node.js 中連接資料庫的步驟:安裝 MySQL、MongoDB 或 PostgreSQL 套件。建立資料庫連接物件。打開資料庫連接,並處理連接錯誤。

nodejs怎麼連接資料庫

如何在Node.js 中連接資料庫

連接MySQL 資料庫

要連接MySQL 資料庫,可以使用下列步驟:

  1. 安裝mysql 套件:npm install mysql
  2. ##建立一個資料庫連接物件:
  3. <code class="typescript">const mysql = require('mysql');
    
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'username',
      password: 'password',
      database: 'database_name'
    });</code>
    開啟資料庫連線:
  1. <code class="typescript">connection.connect((err) => {
      if (err) {
        console.log('Error connecting to database:', err);
        return;
      }
      console.log('Connected to MySQL database');
    });</code>

連接MongoDB 資料庫

要連接MongoDB 資料庫,可以使用以下步驟:

    安裝
  1. mongodb 套件:npm install mongodb
  2. 建立一個資料庫連接物件:
  3. <code class="typescript">const mongo = require('mongodb');
    
    const MongoClient = mongo.MongoClient;
    const url = 'mongodb://localhost:27017';</code>
    開啟資料庫連線:
  1. ##
    <code class="typescript">MongoClient.connect(url, (err, client) => {
      if (err) {
        console.log('Error connecting to database:', err);
        return;
      }
      console.log('Connected to MongoDB database');
    
      // 使用 client 对象进行数据库操作
    });</code>
連接PostgreSQL 資料庫

要連接PostgreSQL 資料庫,可以使用下列步驟:

安裝
    pg
  1. 套件:npm install pg建立一個資料庫連接物件:
  2. <code class="typescript">const pg = require('pg');
    
    const connectionString = 'postgres://username:password@localhost:5432/database_name';
    
    const client = new pg.Client(connectionString);</code>
####################################################開啟資料庫連線:######
<code class="typescript">client.connect((err) => {
  if (err) {
    console.log('Error connecting to database:', err);
    return;
  }
  console.log('Connected to PostgreSQL database');
});</code>

以上是nodejs怎麼連接資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn