在Ubuntu系統中,使用JavaScript連接數據庫通常是通過Node.js來實現的。以下是一些常見數據庫的連接方法:
使用mysql
模塊來連接MySQL數據庫。
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 database.');
});
// 執行查詢
connection.query('SELECT * FROM your_table', (err, results, fields) => {
if (err) throw err;
console.log('Query results:', results);
});
// 關閉連接
connection.end();
使用mongodb
模塊來連接MongoDB數據庫。
mongodb
模塊npm install mongodb
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
const dbName = 'your_database';
// Create a new MongoClient
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
// Use connect method to connect to the server
await client.connect();
console.log('Connected to MongoDB');
// Select the database
const db = client.db(dbName);
// Perform actions on the collection object
const collection = db.collection('your_collection');
const query = { name: 'John' };
const result = await collection.findOne(query);
console.log('Query result:', result);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.error);
使用pg
模塊來連接PostgreSQL數據庫。
pg
模塊npm install pg
const { Client } = require('pg');
// Create a new instance of Client
const client = new Client({
user: 'your_username',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
// Connect to the database
client.connect();
// Execute a query
client.query('SELECT * FROM your_table', (err, res) => {
if (err) throw err;
console.log('Query results:', res.rows);
});
// Close the connection
client.end();
以上是使用Node.js連接不同數據庫的基本方法。你可以根據自己的需求選擇合適的數據庫和模塊,并按照示例代碼進行配置和使用。記得在連接數據庫時,確保數據庫服務已經啟動并且配置正確。