NodeJS
这次我想分享一个在 Node.js 和 MySQL 中进行 CRUD 操作的基本且简单的示例。在 MySQL 中找到 Node.js 教程有点困难,因为人们倾向于使用 Mongoose 而不是 MySQL。开始之前,请注意此应用程序的环境。
我还没有在 Windows 上测试过。但我打赌这也会起作用。
在 Ubuntu 中安装 Node.js、NPM 和 Express
安装完成后,让我们开始创建您的项目文件夹:
ubuntu@AcerXtimeline:~$ express hello_world
hello_world 文件夹准备就绪后,安装 MySQL。进入 hello_world
ubuntu@AcerXtimeline:~/hello_world$ npm install mysql<br>
我们需要 Express 中的连接管理器。安装它
ubuntu@AcerXtimeline:~/hello_world$ npm install express-myconnection
现在看看这个文件夹结构
看看你的文件夹结构,将其与上图进行比较。创建你还没有的新文件夹/文件就像图片上一样在文件夹中。
我们准备好了吗?
1。管理 MySQL 数据库:nodejs 并创建表客户(id、姓名、地址、电子邮件、电话)。 或者你可以在源代码中导入 SQL(见本文末尾)
2.打开 app.js 。默认情况下,已经为您提供了一些代码。我们只需要添加更多代码。
/**<br> * Module dependencies.<br> */<br>var express = require('express');<br>var routes = require('./routes');<br>var http = require('http');<br>var path = require('path');<br>//load customers route<br>var customers = require('./routes/customers'); <br>var app = express();<br>var connection= require('express-myconnection'); <br>var mysql = require('mysql');<br>// all environments<br>app.set('port', process.env.PORT || 4300);<br>app.set('views', path.join(__dirname, 'views'));<br>app.set('view engine', 'ejs');<br>//app.use(express.favicon());<br>app.use(express.logger('dev'));<br>app.use(express.json());<br>app.use(express.urlencoded());<br>app.use(express.methodOverride());<br>app.use(express.static(path.join(__dirname, 'public')));<br>// development only<br>if ('development' == app.get('env')) {<br>app.use(express.errorHandler());<br>}<br>/*------------------------------------------<br>connection peer, register as middleware<br>type koneksi : single,pool and request <br>-------------------------------------------*/<br>app.use(<br><br>connection(mysql,{<br><br>host: 'localhost',<br>user: 'root',<br>password : '',<br>port : 3306, //port mysql<br>database:'nodejs'<br>},'request')<br>);//route index, hello world<br>app.get('/', routes.index);//route customer list<br>app.get('/customers', customers.list);//route add customer, get n post<br>app.get('/customers/add', customers.add);<br>app.post('/customers/add', customers.save);//route delete customer<br>app.get('/customers/delete/:id', customers.delete_customer);//edit customer route , get n post<br>app.get('/customers/edit/:id', customers.edit); <br>app.post('/customers/edit/:id',customers.save_edit);<br>app.use(app.router);<br>http.createServer(app).listen(app.get('port'), function(){<br>console.log('Express server listening on port ' + app.get('port'));<br>});
记住创建新文件/文件夹,如上图所示。
现在,我们需要代码来进行增删改查。文件位于routes/customers.js
/*<br> * GET customers listing.<br> */<br>exports.list = function(req, res){<br>req.getConnection(function(err,connection){<br> <br> connection.query('SELECT * FROM customer',function(err,rows) {<br><br>if(err)<br> console.log("Error Selecting : %s ",err );<br> <br>res.render('customers',{page_title:"Customers - Node.js",data:rows});<br> <br> });<br> <br>});<br><br>};<br>exports.add = function(req, res){<br>res.render('add_customer',{page_title:"Add Customers-Node.js"});<br>};<br>exports.edit = function(req, res){<br><br>var id = req.params.id;<br><br>req.getConnection(function(err,connection){<br> <br> connection.query('SELECT * FROM customer WHERE id = ?',[id],function(err,rows)<br>{<br><br>if(err)<br>console.log("Error Selecting : %s ",err );<br> <br>res.render('edit_customer',{page_title:"Edit Customers - Node.js",data:rows});<br> <br> });<br> <br>}); <br>};<br>/*Save the customer*/<br>exports.save = function(req,res){<br><br>var input = JSON.parse(JSON.stringify(req.body));<br><br>req.getConnection(function (err, connection) {<br><br>var data = {<br><br>name: input.name,<br>address : input.address,<br>email : input.email,<br>phone : input.phone <br><br>};<br><br>var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)<br>{<br><br>if (err)<br>console.log("Error inserting : %s ",err );<br> <br>res.redirect('/customers');<br><br>});<br><br> // console.log(query.sql); get raw query<br><br>});<br>};<br>exports.save_edit = function(req,res){<br><br>var input = JSON.parse(JSON.stringify(req.body));<br>var id = req.params.id;<br><br>req.getConnection(function (err, connection) {<br><br>var data = {<br><br>name: input.name,<br>address : input.address,<br>email : input.email,<br>phone : input.phone <br><br>};<br><br>connection.query("UPDATE customer set ? WHERE id = ? ",[data,id], function(err, rows)<br>{<br><br>if (err)<br>console.log("Error Updating : %s ",err );<br> <br>res.redirect('/customers');<br><br>});<br><br>});<br>};<br><br>exports.delete_customer = function(req,res){<br><br> var id = req.params.id;<br><br> req.getConnection(function (err, connection) {<br><br>connection.query("DELETE FROM customerWHERE id = ? ",[id], function(err, rows)<br>{<br><br> if(err)<br> console.log("Error deleting : %s ",err );<br><br> res.redirect('/customers');<br> <br>});<br><br> });<br>};
<%- include layouts/header.ejs %><br><div class="page-data"><br> <div class="data-btn"><br> <button onClick="addUser();">+ Add</button><br> </div><br> <div class="data-table"><br><table border="1" cellpadding="7" cellspacing="7"><br><tr><br><th width="50px">No</th><br><th>Name</th><br><th>Address</th><br><th>Phone</th><br><th>Email</th><br><th width="120px">Action</th><br></tr> <br><% if(data.length){ <br /><br /> for(var i = 0;i < data.length;i++) { %> <br><tr><br><td><%=(i+1)%></td><br><td><%=data[i].name%></td><br><td><%=data[i].address%></td><br><td><%=data[i].phone%></td><br><td><%=data[i].email%></td><br><td><br><a class="a-inside edit" href="../customers/edit/<%=data[i].id%>">Edit</a> <br><a class="a-inside delete" href="../customers/delete/<%=data[i].id%>">Delete</a> <br></td><br></tr><br><% }<br /><br /> }else{ %><br> <tr><br><td colspan="3">No user</td><br> </tr><br><% } %><br> <br></table><br> </div><br></div><br><%- include layouts/footer.ejs %>
好吧,其实我懒得把它全部写出来这里...这将是一个很长的卷轴:(。请原谅我。我想你可以在此处下载源代码nodecrud,然后在下面的评论中提出疑问或问题。
运行源代码:
ubuntu@AcerXtimeline:~/hello_world$ node app.js
http://localhost:4300/customers<br>
源代码将产生如下内容:
快乐编码