Tag: mysql

Learning Node.Js – Using MySql

 

nodejs-380x300So much buzz about Node.Js I had to give it a try, and let me tell you, I was impressed by the fast results and applicability of this framework (I know… there is a lot of debate about what Node.Js is).

I will not introduce Node.Js or give a tutorial about it, you must know a little about JavaScript and know about request, response and HTTP codes.

This example shows how easy is to develop a http Node.Js server and I can you start using it to access MySql databases with just a few lines of code.

 

Preparation:

1) Download and install Node.Js (its very simple, download and unzip, that’s it!). http://nodejs.org/download/

2) Install the MySql package to access a MySql database.

I’ve used Windows for my learning but it will work for sure in Linux and other platforms.

Just write “npm install mysql”, and the rest speaks for itself. (npm it’s a package manager easily install “add ons” to Node.Js)

D:\node>npm install mysql
npm http GET
https://registry.npmjs.org/mysql
npm http 304 https://registry.npmjs.org/mysql
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/require-all/0.0.3
npm http 304 https://registry.npmjs.org/bignumber.js/1.0.1
npm http GET https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
npm http 200 https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
mysql@2.0.0-alpha8 node_modules\mysql
├── require-all@0.0.3
└── bignumber.js@1.0.1

3) Now we are ready to develop our first web server in JavaScript (don’t worry about being JavaScript, it is written in C/C++ and its very fast. I’ve made simple tests with 500 request per second on my laptop without any flaw).

















































 

 

4) Open a command prompt (console) window and run node for this JavaScript:

D:\node>node testaMySql.js

5) Use a browser or use curl to test it! (If you use curl you simple open another console window)

D:\node>\tools\curl.exe http://localhost:8080

6) And you will see the output in the 2 console windows:

The console output goes to windows which started node. The res calls in the JavaScript goes to the browser or the console running the curl.

 

This is just a start with some “tutorial” example to access a mysql database. Of course you can increase the quality of the code and implement the web server to listen as a  “REST”/HTTP solution.

Technorati Tags: ,,
del.icio.us Tags: ,,

Bad Behavior has blocked 162 access attempts in the last 7 days.

Hyper Smash