本文介紹如何在Linux系統(tǒng)中使用Node.JS連接不同類型的數(shù)據(jù)庫。 請確保已安裝Node.js及相關(guān)數(shù)據(jù)庫驅(qū)動程序。
- 安裝mysql驅(qū)動:
npm install mysql
- 創(chuàng)建連接文件 (例如:db.js):
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: '你的用戶名', password: '你的密碼', database: '你的數(shù)據(jù)庫名' }); connection.connect(err => { if (err) { console.error('數(shù)據(jù)庫連接失敗:', err); return; } console.log('MySQL數(shù)據(jù)庫連接成功!'); }); // 在此處添加你的數(shù)據(jù)庫操作代碼 connection.end();
請?zhí)鎿Q你的用戶名、你的密碼和你的數(shù)據(jù)庫名為你的實際數(shù)據(jù)庫憑據(jù)。
二、連接postgresql數(shù)據(jù)庫
- 安裝PostgreSQL驅(qū)動:
npm install pg
- 創(chuàng)建連接文件 (例如:db.js):
const { Client } = require('pg'); const client = new Client({ host: 'localhost', user: '你的用戶名', password: '你的密碼', database: '你的數(shù)據(jù)庫名', port: 5432 // PostgreSQL默認(rèn)端口 }); client.connect(err => { if (err) { console.error('數(shù)據(jù)庫連接失敗:', err); return; } console.log('PostgreSQL數(shù)據(jù)庫連接成功!'); }); // 在此處添加你的數(shù)據(jù)庫操作代碼 client.end();
同樣,請?zhí)鎿Q占位符為你的實際數(shù)據(jù)庫信息。
三、連接mongodb數(shù)據(jù)庫
- 安裝MongoDB驅(qū)動:
npm install mongodb
- 創(chuàng)建連接文件 (例如:db.js):
const { MongoClient } = require('mongodb'); const uri = 'mongodb://你的用戶名:你的密碼@localhost:27017/你的數(shù)據(jù)庫名'; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); client.connect(err => { if (err) { console.error('數(shù)據(jù)庫連接失敗:', err); return; } console.log('MongoDB數(shù)據(jù)庫連接成功!'); // 在此處添加你的數(shù)據(jù)庫操作代碼 client.close(); });
請將占位符替換為你的MongoDB連接字符串。
以上示例展示了在Linux環(huán)境下使用Node.js連接MySQL、PostgreSQL和MongoDB數(shù)據(jù)庫的基本方法。 你可以根據(jù)實際情況調(diào)整代碼并連接其他類型的數(shù)據(jù)庫。 記住替換示例中的占位符為你的實際數(shù)據(jù)庫信息。