在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连接不同数据库的基本方法。你可以根据自己的需求选择合适的数据库和模块,并按照示例代码进行配置和使用。记得在连接数据库时,确保数据库服务已经启动并且配置正确。