ubuntu

ubuntu中js如何连接数据库

小樊
52
2025-08-23 21:42:29
栏目: 编程语言

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

0
看了该问题的人还看了