在本教程中,我将与您分享如何使用node.js和mysql创建CRUD(创建读取更新删除)应用程序。
不仅如此,我还将分享如何使用引导程序模式进行输入和更新表单。
这样,CRUD应用程序将具有响应性并且对用户友好。
让我们开始吧。
第1步、介绍
这个很重要!
在本教程中,您将学习如何使用node.js和mysql创建CRUD操作。
在本教程中,我将使用Bootstrap和Jquery。
如果没有引导和jQuery,请下载它的官方网站上getbootstrap.com和jquery.com。
第2步、创建数据库结构
创建一个新数据库,在这里我创建一个名为crud_db的数据库。
如果使用相同的名称创建它,则更好。
要在MySQL中创建数据库,可以通过执行以下查询来完成:
CREATE
DATABASE
crud_db;
上面的SQL命令将创建一个名为crud_db的数据库。
接下来,在crud_db数据库中创建一个表。
在这里,我创建了一个名为“ product ”的表。
如果使用相同的名称创建它,则更好。
要创建“产品”表,可以通过执行以下SQL命令来完成:
CREATE TABLE `product` (
`product_id` INT(10,0) NOT NULL AUTO_INCREMENT,
`product_name` VARCHAR(200) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`product_price` INT(10,0) NULL DEFAULT NULL,
PRIMARY KEY (`product_id`) USING BTREE
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;
上面的SQL命令将创建一个具有以下字段的“ product ”表:product_id,product_name和product_price。
第3步、安装依赖项
在安装依赖项之前,请创建一个NetBeans Project,并将其命名为nodejs-mysql-crud。
如下图所示:
在本教程中,我们需要以下4个依赖项:
1. Express(node.js框架)
2. MySQL(node.js的mysql驱动程序)
3.Body-parser(用于处理正文请求的中间件)
4.Handlebars (模板引擎)
使用“ NPM”(节点程序包管理器)可以很容易地在node.js上安装依赖项。
您可以在“终端”或“命令提示符”中运行NPM。
但是,在本教程中,我不使用命令提示符,而是使用NetBeans IDE Project右键菜单中的npm install。
在安装依赖项之前,我们需要为项目创建package.json文件。
NetBeans IDE创建项目时自动创建一个package.json文件。
打开并修改package.json文件,它将如下所示:
{
"name": "nodejs-mysql-crud",
"version": "1.0.0",
"keywords": [
"util",
"functional",
"server",
"client",
"browser"
],
"author": "Administrator",
"contributors": [],
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3",
"hbs": "^4.0.1",
"mysql": "^2.16.0"
}
}
也可以通过在终端中键入以下命令来安装所需的所有依赖项:
npm install --save express mysql body-parser hbs
上面的命令将安装您需要的所有依赖项:express,mysql,body-parser和handlebars。
第4步、项目结构
然后在NetBeans IDE项目Sources中创建一个新文件夹。在这里,我创建了两个文件夹,public和views文件夹。
如下图所示:
之后,在公共文件夹内创建css和js文件夹。
然后将先前下载的bootstrap.css文件复制到public / css /文件夹中。
然后将bootstrap.js和jquery文件复制到public / js /文件夹中。
这样我们的项目结构如下图所示:
第5步、Index.js
创建一个名为index.js的文件。如下图所示:
然后打开index.js并输入以下代码:
//use path module
const path = require('path');
//use express module
const express = require('express');
//use hbs view engine
const hbs = require('hbs');
//use bodyParser middleware
const bodyParser = require('body-parser');
//use mysql database
const mysql = require('mysql');
const app = express();
//Create connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'crud_db'
});
//connect to database
conn.connect((err) => {
if (err)
throw err;
console.log('Mysql Connected...');
});
//set views file
app.set('views', path.join(__dirname, 'views'));
//set view engine
app.set('view engine', 'hbs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//set public folder as static folder for static file
app.use('/assets', express.static(__dirname + '/public'));
//route for homepage
app.get('/', (req, res) => {
let sql = "SELECT * FROM product";
let query = conn.query(sql, (err, results) => {
if (err)
throw err;
res.render('product_view', {
results: results
});
});
});
//route for insert data
app.post('/save', (req, res) => {
let data = {product_name: req.body.product_name, product_price: req.body.product_price};
let sql = "INSERT INTO product SET ?";
let query = conn.query(sql, data, (err, results) => {
if (err)
throw err;
res.redirect('/');
});
});
//route for update data
app.post('/update', (req, res) => {
let sql = "UPDATE product SET product_name='" + req.body.product_name + "', product_price='" + req.body.product_price + "' WHERE product_id=" + req.body.id;
let query = conn.query(sql, (err, results) => {
if (err)
throw err;
res.redirect('/');
});
});
//route for delete data
app.post('/delete', (req, res) => {
let sql = "DELETE FROM product WHERE product_id=" + req.body.product_id + "";
let query = conn.query(sql, (err, results) => {
if (err)
throw err;
res.redirect('/');
});
});
//server listening
app.listen(8000, () => {
console.log('Server is running at port 8000');
});
第6步、视图
在views文件夹中创建一个名为product_view.hbs的文件。如下图:
然后打开product_view.hbs并键入以下代码:
<html lang="en">
<head>
<meta charset="utf-8">
<title>CRUD Node.js and Mysql</title>
<link href="/assets/css/bootstrap.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<h2>Product List</h2>
<button class="btn btn-success" data-toggle="modal" data-target="#myModalAdd">Add New</button>
<table class="table table-striped" id="mytable">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{{#each results}}
<tr>
<td>{{ product_id }}</td>
<td>{{ product_name }}</td>
<td>{{ product_price }}</td>
<td>
<a href="javascript:void(0);" class="btn btn-sm btn-info edit" data-id="{{ product_id }}" data-product_name="{{ product_name }}" data-product_price="{{ product_price }}">Edit</a>
<a href="javascript:void(0);" class="btn btn-sm btn-danger delete" data-id="{{ product_id }}">Delete</a>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<!-- Modal Add Product-->
<form action="/save" method="post">
<div class="modal fade" id="myModalAdd" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="product_name" class="form-control" placeholder="Product Name" required>
</div>
<div class="form-group">
<input type="text" name="product_price" class="form-control" placeholder="Price" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
<!-- Modal Update Product-->
<form action="/update" method="post">
<div class="modal fade" id="EditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="product_name" class="form-control product_name" placeholder="Product Name" required>
</div>
<div class="form-group">
<input type="text" name="product_price" class="form-control price" placeholder="Price" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="id" class="product_id">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</div>
</div>
</form>
<!-- Modal Delete Product-->
<form id="add-row-form" action="/delete" method="post">
<div class="modal fade" id="DeleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="myModalLabel">Delete Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<strong>Are you sure to delete this data?</strong>
</div>
<div class="modal-footer">
<input type="hidden" name="product_id" class="form-control product_id2" required>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Delete</button>
</div>
</div>
</div>
</div>
</form>
<script src="/assets/js/jquery-3.6.0.js"></script>
<script src="/assets/js/bootstrap.js"></script>
<script>
$(document).ready(function(){
//showing data to edit modal $('#mytable').on('click','.edit',function(){
var product_id = $(this).data('id');
var product_name = $(this).data('product_name');
var product_price = $(this).data('product_price');
$('#EditModal').modal('show');
$('.product_name').val(product_name);
$('.price').val(product_price);
$('.product_id').val(product_id);
});
//showing delete record modal
$('#mytable').on('click','.delete',function(){
var product_id = $(this).data('id');
$('#DeleteModal').modal('show');
$('.product_id2').val(product_id);
});
});
</script>
</body>
</html>
第7步、测试
测试该应用程序,以确保我们创建的原始应用程序运行良好。
要运行该应用程序,请鼠标右键点击index.文件,在右键菜单中选择Run File。
或在终端上键入以下命令。
node index
然后它将出现在控制台消息“服务器正在端口8000上运行”和“ Mysql Connected”上。
如下图所示:
然后打开浏览器并输入以下URL:
如果运行良好,则它将如下图所示:
单击“添加新产品”按钮,然后将出现“添加新产品”模式,如下图所示:
然后输入产品名称和价格,然后单击保存按钮。
然后您可以看到如下图所示的结果:
单击“编辑”按钮以编辑记录,然后将出现“编辑产品”模式,如下图所示:
编辑要编辑的数据,然后单击“更新”按钮。
然后您可以看到如下图所示的结果:
要删除记录,请单击“删除”按钮,然后将显示确认模式,如下所示:
然后单击删除按钮删除记录。
完成。
结论:
今天的教程是关于如何使用node.js和mysql构建CRUD应用程序(创建读取更新删除)的。
在本教程中,您学习了如何使用node.js和mysql制作CRUD应用程序。
不仅如此,您还学习了如何将引导程序模式用于输入和更新表单。
那你还在等什么。让我们编码吧!