溫馨提示×

Node.js在CentOS上的數據庫連接如何配置

小樊
48
2025-03-11 12:12:05
欄目: 編程語言

在CentOS上使用Node.js連接數據庫,通常需要以下幾個步驟:

  1. 安裝Node.js

首先,確保你已經在CentOS上安裝了Node.js。如果還沒有安裝,可以使用以下命令安裝:

curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs

這將安裝Node.js的長期支持(LTS)版本。你可以根據需要更改版本號。

  1. 安裝數據庫

根據你使用的數據庫類型,在CentOS上安裝相應的數據庫。例如,如果你使用的是MySQL,可以使用以下命令安裝:

sudo yum install -y mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld

對于PostgreSQL,可以使用以下命令安裝:

sudo yum install -y postgresql-server
sudo systemctl start postgresql
sudo systemctl enable postgresql
  1. 安裝數據庫驅動

在Node.js項目中,你需要安裝相應的數據庫驅動。以下是一些常見數據庫的驅動:

  • MySQL: npm install mysql
  • PostgreSQL: npm install pg
  • MongoDB: npm install mongodb
  • SQLite3: npm install sqlite3
  1. 配置數據庫連接

在Node.js項目中,創建一個新的JavaScript文件(例如app.js),并使用以下代碼配置數據庫連接。請根據你的數據庫類型和憑據替換相應的值。

  • MySQL示例:
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('Connected to the database!');
});

// Your database operations go here

connection.end();
  • PostgreSQL示例:
const { Client } = require('pg');

const client = new Client({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

client.connect(error => {
  if (error) throw error;
  console.log('Connected to the database!');
});

// Your database operations go here

client.end();
  1. 運行Node.js應用程序

在終端中,導航到你的Node.js項目目錄,然后運行以下命令:

node app.js

這將啟動你的Node.js應用程序,并連接到配置的數據庫?,F在你可以執行數據庫操作,如查詢、插入、更新和刪除數據。

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