Usually in NODEJS development we often involve the operation of the database, especially MySQL, as the most widely used open source database is our first choice, this article describes how to operate the MySQL database through Nodejs. Installing the MySQL module into Nodejs we need to get Nodejs to support MySQL, then we need to add the MySQL module to the System support library
Installing Node-mysql
Create a test table
Connecting to a database
var sys = require (' sys '); var Client = require (' MySQL '). Client; var client = new Client (); Client.user = ' Someuser '; Client.password = ' password ';
Open Database
Complete the database Operation program
var sys = require (' sys '); var Client = require (' MySQL '). Client; var client = new Client (); Client.user = ' Someuser '; Client.password = ' password '; Console.log (' Connecting to MySQL ... '); Client.connect (function (error, results) {if (error) {console.log (' Connection error: ' + error.message); return;} console . log (' Connected to MySQL '); Clientconnectionready (client); }); Clientconnectionready = function (client) {client.query (' use Nodesample ', function (error, results) {if (error) {Console. Log (' Clientconnectionready Error: ' + error.message); Client.end (); Return } clientready (client); }); }; Clientready = function (client) {var values = [' Chad ', ' Lung ', ' Hello World ']; Client.query (' INSERT into MyTable SET first Name =?, LastName =? , message =? ', values, function (error, results) {if (error) {Console.log ("Clientready error:" + error.message); Client.end (); Return } console.log (' Inserted: ' + results.affectedrows + ' row '); Console.log (' Id inserted: ' + Results.insertid); } ); GetData (client); } GetData = function (client) {client.query (' SELECT * from MyTable ', function SELECTCB (Error, results, fields) {if (err OR) {Console.log (' GetData Error: ' + error.message); Client.end (); return;}//Uncomment these if you want lots of feedb Ack//console.log (' Results: '); Console.log (results); Console.log (' Field metadata: '); Console.log (fields); Console.log (Sys.inspect (results)); if (Results.length > 0) {var firstresult = results[0]; Console.log (' First Name: ' + firstresult[' FirstName ']); console. Log (' last Name: ' + firstresult[' LastName '); Console.log (' message: ' + firstresult[' message '); } }); Client.end (); Console.log (' Connection closed '); };
node. JS connects to MySQL and makes database operations