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

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
<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><br> for(var i = 0;i <br><tr> <br><td></td> <br><td></td> <br><td></td> <br><td></td> <br><td></td> <br><td> <br><a class="a-inside edit" href="../customers/edit/<%=data%5Bi%5D.id%>">Edit</a> <br><a class="a-inside delete" href="../customers/delete/<%=data%5Bi%5D.id%>">Delete</a> <br> </td> <br> </tr> <br><br> }else{ %><br> <tr> <br><td colspan="3">No user</td> <br> </tr> <br><br> <br> </table> <br> </div> <br> </div><br>
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:




InnoDB는 Redologs 및 Undologs를 사용하여 데이터 일관성과 신뢰성을 보장합니다. 1. Redologs는 사고 복구 및 거래 지속성을 보장하기 위해 데이터 페이지 수정을 기록합니다. 2. 결점은 원래 데이터 값을 기록하고 트랜잭션 롤백 및 MVCC를 지원합니다.

설명 명령에 대한 주요 메트릭에는 유형, 키, 행 및 추가가 포함됩니다. 1) 유형은 쿼리의 액세스 유형을 반영합니다. 값이 높을수록 Const와 같은 효율이 높아집니다. 2) 키는 사용 된 인덱스를 표시하고 NULL은 인덱스가 없음을 나타냅니다. 3) 행은 스캔 한 행의 수를 추정하여 쿼리 성능에 영향을 미칩니다. 4) Extra는 최적화해야한다는 Filesort 프롬프트 사용과 같은 추가 정보를 제공합니다.

Temporary를 사용하면 MySQL 쿼리에 임시 테이블을 생성해야 할 필요성이 있으며, 이는 별개의, 그룹 비 또는 비 인덱스 열을 사용하여 순서대로 발견됩니다. 인덱스 발생을 피하고 쿼리를 다시 작성하고 쿼리 성능을 향상시킬 수 있습니다. 구체적으로, 설명 출력에 사용되는 경우, MySQL은 쿼리를 처리하기 위해 임시 테이블을 만들어야 함을 의미합니다. 이것은 일반적으로 다음과 같은 경우에 발생합니다. 1) 별개 또는 그룹을 사용할 때 중복 제거 또는 그룹화; 2) OrderBy가 비 인덱스 열이 포함되어있을 때 정렬하십시오. 3) 복잡한 하위 쿼리 또는 조인 작업을 사용하십시오. 최적화 방법은 다음과 같습니다. 1) Orderby 및 GroupB

MySQL/InnoDB는 4 개의 트랜잭션 격리 수준을 지원합니다. Readuncommitted, ReadCommitted, ReturableRead 및 Serializable. 1. READUCMITTED는 커밋되지 않은 데이터를 읽을 수 있으므로 더러운 판독 값을 유발할 수 있습니다. 2. ReadCommitted는 더러운 읽기를 피하지만 반복 할 수없는 독서가 발생할 수 있습니다. 3. RepeatableRead는 더러운 읽기와 반복 할 수없는 독서를 피하는 기본 레벨이지만 팬텀 독서가 발생할 수 있습니다. 4. 직렬화 가능한 것은 모든 동시성 문제를 피하지만 동시성을 줄입니다. 적절한 격리 수준을 선택하려면 균형 잡힌 데이터 일관성 및 성능 요구 사항이 필요합니다.

MySQL은 웹 응용 프로그램 및 컨텐츠 관리 시스템에 적합하며 오픈 소스, 고성능 및 사용 편의성에 인기가 있습니다. 1) PostgreSQL과 비교하여 MySQL은 간단한 쿼리 및 높은 동시 읽기 작업에서 더 잘 수행합니다. 2) Oracle과 비교할 때 MySQL은 오픈 소스와 저렴한 비용으로 인해 중소 기업에서 더 인기가 있습니다. 3) Microsoft SQL Server와 비교하여 MySQL은 크로스 플랫폼 응용 프로그램에 더 적합합니다. 4) MongoDB와 달리 MySQL은 구조화 된 데이터 및 트랜잭션 처리에 더 적합합니다.

MySQL Index Cardinality는 쿼리 성능에 중대한 영향을 미칩니다. 1. 높은 카디널리티 인덱스는 데이터 범위를보다 효과적으로 좁히고 쿼리 효율성을 향상시킬 수 있습니다. 2. 낮은 카디널리티 인덱스는 전체 테이블 스캔으로 이어질 수 있으며 쿼리 성능을 줄일 수 있습니다. 3. 관절 지수에서는 쿼리를 최적화하기 위해 높은 카디널리티 시퀀스를 앞에 놓아야합니다.

MySQL 학습 경로에는 기본 지식, 핵심 개념, 사용 예제 및 최적화 기술이 포함됩니다. 1) 테이블, 행, 열 및 SQL 쿼리와 같은 기본 개념을 이해합니다. 2) MySQL의 정의, 작업 원칙 및 장점을 배우십시오. 3) 인덱스 및 저장 절차와 같은 기본 CRUD 작업 및 고급 사용량을 마스터합니다. 4) 인덱스의 합리적 사용 및 최적화 쿼리와 같은 일반적인 오류 디버깅 및 성능 최적화 제안에 익숙합니다. 이 단계를 통해 MySQL의 사용 및 최적화를 완전히 파악할 수 있습니다.

MySQL의 실제 응용 프로그램에는 기본 데이터베이스 설계 및 복잡한 쿼리 최적화가 포함됩니다. 1) 기본 사용 : 사용자 정보 삽입, 쿼리, 업데이트 및 삭제와 같은 사용자 데이터를 저장하고 관리하는 데 사용됩니다. 2) 고급 사용 : 전자 상거래 플랫폼의 주문 및 재고 관리와 같은 복잡한 비즈니스 로직을 처리합니다. 3) 성능 최적화 : 인덱스, 파티션 테이블 및 쿼리 캐시를 사용하여 합리적으로 성능을 향상시킵니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.
