Example of CRUD with Node.js & MySQL_MySQL

php中文网
发布: 2016-06-01 13:16:30
原创
1599人浏览过

NodeJS

This time I'd like to share a basic and simple example of CRUD Operation in Node.js and MySQL. Its a lil bit hard to find tutorial Node.js n MySQL as poeple tend to use Mongoose instead of MySQL. 

before we start, please mind the environment of this application.

  • I'm using Ubuntu
  • NPM, Express 
  • MySQL for Node

I haven't tested it yet on Windows. but i bet this will work too.

Installing all those things above

Install Node.js, NPM and Express in Ubuntu 

After you installation's completed, lets start creating your project folder:

ubuntu@AcerXtimeline:~$ express hello_world
登录后复制

once your hello_world folder is ready, Install MySQL. Go inside hello_world

ubuntu@AcerXtimeline:~/hello_world$ npm install mysql<br />
登录后复制

We need a connection manager in Express. install it 

ubuntu@AcerXtimeline:~/hello_world$ npm install express-myconnection
登录后复制

Now take a look at this Folder structure

Example of CRUD with Node.js &amp; MySQL_MySQL

See you folder structure, compare it to the picture above.make new folder/files that you dont have yet in folder just like on the pic.

Are we ready yet ? 

1. Careate a MySQL Database :nodejs and create a tablecustomer (id,name,address,email,phone).  or you can import the SQL in source code (see the end of this tuts)

2. Open app.js . by default some codes are already given for you. we'll just need to add a lil more codes.

/**<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 />});
登录后复制

remember to make new files/folder like shown on the above pic. 
Now, wee need codes to DO THE CRUD. the file's locatedroutes/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 />};
登录后复制

here's html code (ejs template) for listing the customer
<%- 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 %>
登录后复制

Well, actually 'm too lazy to put it all here...its gonna be a long scroll :(. pardon me for that. I think you can just download the Source herenodecrud and put a questions or issue on the Comment bellow. 

run the the source code :

ubuntu@AcerXtimeline:~/hello_world$ node app.js
登录后复制
http://localhost:4300/customers<br />
登录后复制

The source will produce things like these:

Example of CRUD with Node.js &amp; MySQL_MySQLExample of CRUD with Node.js &amp; MySQL_MySQLExample of CRUD with Node.js &amp; MySQL_MySQLHappy coding
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号