如何在 Node.js 中连接并使用数据库
Node.js 是一种流行的 JavaScript 运行时环境,通常用于构建 Web 应用程序和 API。为了存储和管理数据,Node.js 可以连接到各种数据库系统。
选择一个数据库系统
- 关系型数据库 (RDBMS):例如 MySQL、PostgreSQL,适合于结构化数据和关系查询。
- 非关系型数据库 (NoSQL):例如 MongoDB、Redis,适合于非结构化数据和键值存储。
- 云数据库:例如 AWS DynamoDB、Google Cloud Spanner,提供可扩展、高可用性的数据库解决方案。
建立连接
Node.js 有多种用于与数据库交互的模块。以下是每个数据库类型的常用模块:
-
MySQL:
<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15713.html" target="_blank">mysql</a>
或mysql2
-
PostgreSQL:
pg
-
MongoDB:
<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/16002.html" target="_blank">mongodb</a>
-
Redis:
<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15737.html" target="_blank">redis</a>
要建立连接,可以使用以下代码模板:
<code class="javascript">const { createConnection } = require(\'mysql\'); const conn = createConnection({ host: \'localhost\', port: 3306, user: \'root\', password: \'\', database: \'mydb\' });