使用 Node.js 连接 MySQL 数据库的步骤如下:安装 MySQL 客户端库创建 MySQL 连接连接到 MySQL 数据库查询数据库关闭连接
如何使用 Node.js 连接 MySQL
要使用 Node.js 连接 MySQL 数据库,需要遵循以下步骤:
1. 安装 MySQL 客户端库
npm install mysql
2. 创建 MySQL 连接
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'my_password', database: 'my_database' });
3. 连接到 MySQL 数据库
connection.connect((err) => { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); });
4. 查询数据库
connection.query('SELECT * FROM my_table', (err, rows) => { if (err) { console.error('error querying: ' + err.stack); return; } console.log('rows: ', rows); });
5. 关闭连接
connection.end((err) => { // ... });
其他连接选项
MySQL 客户端库还提供了其他连接选项,包括:
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号