在 Ubuntu 上,使用 Node.js 连接数据库有多种方法,具体取决于你使用的数据库类型(如 MySQL、PostgreSQL、MongoDB 等)。以下是使用 Node.js 连接 MySQL 和 MongoDB 的基本步骤:
安装 MySQL 服务器:
sudo apt update
sudo apt install mysql-server
安装 Node.js 和 npm:
sudo apt install nodejs npm
创建一个新的 Node.js 项目:
mkdir my-nodejs-app
cd my-nodejs-app
npm init -y
安装 MySQL 客户端库:
npm install mysql
编写连接 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();
运行代码:
node index.js
安装 MongoDB 服务器:
sudo apt update
sudo apt install -y mongodb
启动 MongoDB 服务:
sudo systemctl start mongod
安装 Node.js 和 npm:
sudo apt install nodejs npm
创建一个新的 Node.js 项目:
mkdir my-nodejs-app
cd my-nodejs-app
npm init -y
安装 MongoDB 客户端库:
npm install mongodb
编写连接 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);
运行代码:
node index.js
通过以上步骤,你可以在 Ubuntu 上使用 Node.js 连接到 MySQL 和 MongoDB 数据库。根据你的具体需求,可能需要调整数据库连接配置和查询语句。