在当今的Web开发领域,Node.js以其高性能和跨平台的特点受到了广泛关注。而Express作为Node.js的Web应用框架,则以其简洁的API和强大的功能深受开发者喜爱。结合MySQL数据库,我们可以构建出功能强大、性能稳定的Web应用。本文将带领大家轻松实现Node.js数据库连接与操作实战。
一、环境准备
在开始之前,我们需要准备以下环境:
- Node.js环境:从官网下载并安装Node.js。
- MySQL数据库:下载并安装MySQL数据库。
- Express框架:通过npm安装Express。
npm install express mysql
二、创建项目结构
创建一个名为express-mysql的项目,并在其中创建以下文件和目录:
express-mysql/
├── node_modules/
├── public/
│ └── index.html
├── routes/
│ └── index.js
├── views/
│ └── layout.hbs
├── app.js
└── package.json
三、配置数据库连接
在app.js文件中,我们需要配置数据库连接。这里我们使用mysql模块来实现。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'test'
});
connection.connect(err => {
if (err) {
console.error('数据库连接失败:', err);
return;
}
console.log('数据库连接成功!');
});
module.exports = connection;
四、创建路由
在routes/index.js文件中,我们创建一个简单的路由来展示如何从数据库中查询数据。
const express = require('express');
const router = express.Router();
const connection = require('../app.js');
router.get('/', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
if (err) {
console.error('查询失败:', err);
return;
}
res.render('index', { users: results });
});
});
module.exports = router;
五、创建视图
在views/index.hbs文件中,我们创建一个简单的HTML页面来展示用户数据。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1>用户列表</h1>
<ul>
{{#each users}}
<li>{{this.name}} - {{this.email}}</li>
{{/each}}
</ul>
</body>
</html>
六、启动项目
在app.js文件中,我们使用Express框架来启动项目。
const express = require('express');
const hbs = require('hbs');
const path = require('path');
const connection = require('./app.js');
const indexRouter = require('./routes/index');
const app = express();
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
hbs.registerPartials(path.join(__dirname, 'views/partials'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
现在,我们已经成功实现了Node.js数据库连接与操作实战。你可以通过访问http://localhost:3000来查看用户列表。
总结
本文介绍了如何使用Express和MySQL在Node.js中实现数据库连接与操作。通过以上步骤,你可以轻松构建出功能强大的Web应用。希望本文对你有所帮助!
