It is a JavaScript toolkit for writing high-performance network servers
Usually in NodeJS development, we often involve operating databases, especially MySQL. As the most widely used open source database, it has become our first choice. This article will introduce how to operate MySQL databases through NodeJS. Installing MySQL module into NodeJS We need to make NodeJS support MySQL, and we need to add MySQL module to the system support library
If you want to get a quick look, please recommend a look at node.js_guide.pdf — Development Guide: If you want an electronic version of high-definition message send
If you don't want to leave a message, you can take you to make a plane!Download directly
Let's briefly introduce the operation
Install node-mysql
C code
$ npm install mysql
Create a test table
//Database name NodeSample
C code
CREATE TABLE `NodeSample`.`MyTable` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `firstname` VARCHAR( 20 ) NOT NULL , `lastname` VARCHAR( 20 ) NOT NULL , `message` TEXT NOT NULL ) ENGINE = MYISAM ;
Connect to the database
Js code
var sys = require('sys'); var Client = require('mysql').Client; var client = new Client(); = 'someuser'; = 'password'; (function(error, results) { if(error) { ('Connection Error: ' + ); return; } ('Connected to MySQL'); });
Open the database
Js code
ClientConnectionReady = function(client) { ('USE NodeSample', function(error, results) { if(error) { ('ClientConnectionReady Error: ' + ); (); return; } }); };
Complete database operation procedures
Js code
var sys = require('sys'); var Client = require('mysql').Client; var client = new Client(); = 'someuser'; = 'password'; ('Connecting to MySQL...'); (function(error, results) { if(error) { ('Connection Error: ' + ); return; } ('Connected to MySQL'); ClientConnectionReady(client); }); ClientConnectionReady = function(client) { ('USE NodeSample', function(error, results) { if(error) { ('ClientConnectionReady Error: ' + ); (); return; } ClientReady(client); }); }; ClientReady = function(client) { var values = ['Chad', 'Lung', 'Hello World']; ('INSERT INTO MyTable SET firstname = ?, lastname = ? , message = ?', values, function(error, results) { if(error) { ("ClientReady Error: " + ); (); return; } ('Inserted: ' + + ' row.'); ('Id inserted: ' + ); } ); GetData(client); } GetData = function(client) { ( 'SELECT * FROM MyTable', function selectCb(error, results, fields) { if (error) { ('GetData Error: ' + ); (); return; } // Uncomment these if you want lots of feedback //('Results:'); //(results); //('Field metadata:'); //(fields); //((results)); if( > 0) { var firstResult = results[0]; ('First Name: ' + firstResult['firstname']); ('Last Name: ' + firstResult['lastname']); ('Message: ' + firstResult['message']); } }); (); ('Connection closed'); };