阅读量:2
在Ubuntu系统中,使用JavaScript连接数据库通常是通过Node.js来实现的。以下是一些常见数据库的连接方法:
1. 连接MySQL数据库
使用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();
2. 连接MongoDB数据库
使用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);
3. 连接PostgreSQL数据库
使用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连接不同数据库的基本方法。你可以根据自己的需求选择合适的数据库和模块,并按照示例代码进行配置和使用。记得在连接数据库时,确保数据库服务已经启动并且配置正确。
以上就是关于“ubuntu中js如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm