検索
ホームページデータベースmysql チュートリアルExample of CRUD with Node.js & MySQL_MySQL

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 & 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
<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:

Example of CRUD with Node.js & MySQL_MySQLExample of CRUD with Node.js & MySQL_MySQLExample of CRUD with Node.js & MySQL_MySQLHappy coding
声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
MySQLはSQLiteとどのように違いますか?MySQLはSQLiteとどのように違いますか?Apr 24, 2025 am 12:12 AM

MySQLとSQLiteの主な違いは、設計コンセプトと使用法のシナリオです。1。MySQLは、大規模なアプリケーションとエンタープライズレベルのソリューションに適しており、高性能と高い並行性をサポートしています。 2。SQLiteは、モバイルアプリケーションとデスクトップソフトウェアに適しており、軽量で埋め込みやすいです。

MySQLのインデックスとは何ですか?また、パフォーマンスをどのように改善しますか?MySQLのインデックスとは何ですか?また、パフォーマンスをどのように改善しますか?Apr 24, 2025 am 12:09 AM

MySQLのインデックスは、データの取得をスピードアップするために使用されるデータベーステーブル内の1つ以上の列の順序付けられた構造です。 1)インデックスは、スキャンされたデータの量を減らすことにより、クエリ速度を改善します。 2)B-Tree Indexは、バランスの取れたツリー構造を使用します。これは、範囲クエリとソートに適しています。 3)CreateIndexステートメントを使用して、createIndexidx_customer_idonorders(customer_id)などのインデックスを作成します。 4)Composite Indexesは、createIndexIDX_CUSTOMER_ORDERONORDERS(Customer_Id、Order_date)などのマルチコラムクエリを最適化できます。 5)説明を使用してクエリ計画を分析し、回避します

データの一貫性を確保するために、MySQLでトランザクションを使用する方法を説明します。データの一貫性を確保するために、MySQLでトランザクションを使用する方法を説明します。Apr 24, 2025 am 12:09 AM

MySQLでトランザクションを使用すると、データの一貫性が保証されます。 1)StartTransactionを介してトランザクションを開始し、SQL操作を実行して、コミットまたはロールバックで送信します。 2)SavePointを使用してSave Pointを設定して、部分的なロールバックを許可します。 3)パフォーマンスの最適化の提案には、トランザクション時間の短縮、大規模なクエリの回避、分離レベルの使用が合理的に含まれます。

どのシナリオでMySQLよりもPostgreSQLを選択できますか?どのシナリオでMySQLよりもPostgreSQLを選択できますか?Apr 24, 2025 am 12:07 AM

MySQLの代わりにPostgreSQLが選択されるシナリオには、1)複雑なクエリと高度なSQL関数、2)厳格なデータの整合性と酸コンプライアンス、3)高度な空間関数が必要、4)大規模なデータセットを処理するときに高いパフォーマンスが必要です。 PostgreSQLは、これらの側面でうまく機能し、複雑なデータ処理と高いデータの整合性を必要とするプロジェクトに適しています。

MySQLデータベースをどのように保護できますか?MySQLデータベースをどのように保護できますか?Apr 24, 2025 am 12:04 AM

MySQLデータベースのセキュリティは、以下の測定を通じて達成できます。1。ユーザー許可管理:CreateUSERおよびGrantコマンドを通じてアクセス権を厳密に制御します。 2。暗号化された送信:SSL/TLSを構成して、データ送信セキュリティを確保します。 3.データベースのバックアップとリカバリ:MySQLDUMPまたはMySQLPumpを使用して、定期的にデータをバックアップします。 4.高度なセキュリティポリシー:ファイアウォールを使用してアクセスを制限し、監査ロギング操作を有効にします。 5。パフォーマンスの最適化とベストプラクティス:インデックス作成とクエリの最適化と定期的なメンテナンスを通じて、安全性とパフォーマンスの両方を考慮に入れます。

MySQLのパフォーマンスを監視するために使用できるツールは何ですか?MySQLのパフォーマンスを監視するために使用できるツールは何ですか?Apr 23, 2025 am 12:21 AM

MySQLのパフォーマンスを効果的に監視する方法は? MySqladmin、ShowGlobalStatus、PerconAmonitoring and Management(PMM)、MySQL EnterpriseMonitorなどのツールを使用します。 1. mysqladminを使用して、接続の数を表示します。 2。showglobalstatusを使用して、クエリ番号を表示します。 3.PMMは、詳細なパフォーマンスデータとグラフィカルインターフェイスを提供します。 4.mysqlenterprisemonitorは、豊富な監視機能とアラームメカニズムを提供します。

MySQLはSQL Serverとどのように違いますか?MySQLはSQL Serverとどのように違いますか?Apr 23, 2025 am 12:20 AM

MySQLとSQLServerの違いは次のとおりです。1)MySQLはオープンソースであり、Webおよび埋め込みシステムに適しています。2)SQLServerはMicrosoftの商用製品であり、エンタープライズレベルのアプリケーションに適しています。ストレージエンジン、パフォーマンスの最適化、アプリケーションシナリオの2つには大きな違いがあります。選択するときは、プロジェクトのサイズと将来のスケーラビリティを考慮する必要があります。

どのシナリオでMySQLよりもSQL Serverを選択できますか?どのシナリオでMySQLよりもSQL Serverを選択できますか?Apr 23, 2025 am 12:20 AM

高可用性、高度なセキュリティ、優れた統合を必要とするエンタープライズレベルのアプリケーションシナリオでは、MySQLの代わりにSQLServerを選択する必要があります。 1)SQLServerは、高可用性や高度なセキュリティなどのエンタープライズレベルの機能を提供します。 2)VisualStudioやPowerbiなどのMicrosoftエコシステムと密接に統合されています。 3)SQLSERVERは、パフォーマンスの最適化に優れた機能を果たし、メモリが最適化されたテーブルと列ストレージインデックスをサポートします。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)