在本章中,我们将探讨如何使用 Node.js 来连接和操作各种数据库。我们将涵盖关系型数据库(如 MySQL 和 PostgreSQL)以及非关系型数据库(如 MongoDB)。通过实际的例子,我们将一步步地展示如何设置环境、安装必要的库、连接到数据库,并执行基本的 CRUD(创建、读取、更新、删除)操作。
安装必要的模块
在开始之前,我们需要确保已经安装了 Node.js 环境。接下来,根据我们选择使用的数据库类型,需要安装相应的模块。例如,如果我们要连接 MySQL 数据库,可以使用 mysql 模块;对于 MongoDB,则需要 mongodb 模块。
使用 npm 安装模块
首先,打开命令行工具,进入你的项目目录。然后,根据你想要使用的数据库类型,运行以下命令之一来安装对应的模块:
对于 MySQL:
npm install mysql
对于 PostgreSQL:
npm install pg
对于 MongoDB:
npm install mongodb
MySQL 数据库连接示例
创建连接
一旦安装了 mysql 模块,就可以开始创建数据库连接了。下面是一个简单的例子,展示了如何建立一个到 MySQL 数据库的连接:
// www.javascriptcn.com code example
const mysql = require('mysql');
// 创建一个连接配置对象
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
// 连接到 MySQL 数据库
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to MySQL database!");
});执行查询
一旦连接成功,就可以执行 SQL 查询了。以下是如何执行一个简单的 SELECT 查询并处理结果的例子:
connection.query('SELECT * FROM users', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results);
});关闭连接
完成所有操作后,记得关闭数据库连接:
connection.end();
PostgreSQL 数据库连接示例
对于 PostgreSQL 数据库,使用 pg 模块来连接和操作数据库。这里有一个简单的例子:
创建连接
// www.javascriptcn.com code example
const { Client } = require('pg');
const client = new Client({
user: 'postgres',
host: 'localhost',
database: 'testdb',
password: 'password',
port: 5432,
});
client.connect();
client.query('SELECT NOW()', (err, res) => {
console.log(err, res)
client.end()
});MongoDB 数据库连接示例
MongoDB 是一个流行的 NoSQL 数据库,非常适合存储大量结构化和非结构化的数据。我们可以使用 mongodb 模块来连接和操作 MongoDB 数据库。
创建连接
// www.javascriptcn.com code example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
await client.connect();
console.log("Connected successfully to server");
const database = client.db('testdb');
const collection = database.collection('users');
// 插入文档
const doc = { name: 'John Doe', age: 30 };
const result = await collection.insertOne(doc);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);以上就是在 Node.js 中连接和操作不同类型的数据库的基本方法。希望这些例子能帮助你更好地理解和使用 Node.js 处理数据库相关的任务。接下来的章节中,我们会深入探讨更多高级主题,包括错误处理、事务管理等。