ubuntu

Ubuntu Nodejs 与数据库如何连接

小樊
45
2025-09-18 10:59:41
栏目: 编程语言

在 Ubuntu 上,使用 Node.js 连接数据库有多种方法,具体取决于你使用的数据库类型(如 MySQL、PostgreSQL、MongoDB 等)。以下是使用 Node.js 连接 MySQL 和 MongoDB 的基本步骤:

连接 MySQL 数据库

  1. 安装 MySQL 服务器

    sudo apt update
    sudo apt install mysql-server
    
  2. 安装 Node.js 和 npm

    sudo apt install nodejs npm
    
  3. 创建一个新的 Node.js 项目

    mkdir my-nodejs-app
    cd my-nodejs-app
    npm init -y
    
  4. 安装 MySQL 客户端库

    npm install mysql
    
  5. 编写连接 MySQL 的代码: 创建一个名为 index.js 的文件,并添加以下代码:

    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(results);
    });
    
    // 关闭连接
    connection.end();
    
  6. 运行代码

    node index.js
    

连接 MongoDB 数据库

  1. 安装 MongoDB 服务器

    sudo apt update
    sudo apt install -y mongodb
    
  2. 启动 MongoDB 服务

    sudo systemctl start mongod
    
  3. 安装 Node.js 和 npm

    sudo apt install nodejs npm
    
  4. 创建一个新的 Node.js 项目

    mkdir my-nodejs-app
    cd my-nodejs-app
    npm init -y
    
  5. 安装 MongoDB 客户端库

    npm install mongodb
    
  6. 编写连接 MongoDB 的代码: 创建一个名为 index.js 的文件,并添加以下代码:

    const { MongoClient } = require('mongodb');
    
    // 连接 URL
    const url = 'mongodb://localhost:27017';
    const dbName = 'your_database';
    
    // 创建 MongoClient 实例
    const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
    
    async function run() {
      try {
        // 使用 connect 方法连接到服务器
        await client.connect();
        console.log('Connected to MongoDB');
    
        // 选择数据库
        const db = client.db(dbName);
    
        // 执行查询
        const collection = db.collection('your_collection');
        const query = { name: 'your_name' };
        const result = await collection.findOne(query);
        console.log(result);
      } finally {
        // 关闭连接
        await client.close();
      }
    }
    
    run().catch(console.error);
    
  7. 运行代码

    node index.js
    

通过以上步骤,你可以在 Ubuntu 上使用 Node.js 连接到 MySQL 和 MongoDB 数据库。根据你的具体需求,可能需要调整数据库连接配置和查询语句。

0
看了该问题的人还看了