Nodejs connect to the MySQL database, first create a database and a table. As follows:
create databases node;
CREATE TABLE test (id int auto_increment PRIMARY KEY, name char ()) Engine=innodb DEFAULT Charset=utf8;
To install the MySQL driver:
Mysql
Here is the Nodejs code:
var sys = require (' util '); Console.log (' Connecting MySQL ... '); var client = require ('MySQL '). CreateClient ({' host ': ' localhost ', ' Port ': 3306, ' user ': ' Root ', ' password ': ' xxx '}); clientconnectionready = function (client) {client.query (' use node ', function (error, results) {if (error) {Console.log (' Cli Entconnectionready Error: ' + error.message); Client.end (); Return }else{Console.log (' already connected to MySQL .... ');} Clientready (client); }); };clientready = function (client) {var values = [' good ah ']; Client.query (' INSERT into test set name =? ', 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 Test ', function SELECTCB(Error, results, fields) {if (error) {console.log (' GetData error: ' + error.message); Client.end (); Return } for (var i=0; i<results.length; i++) {var firstresult = results[i]; Console.log (' ID: ' + firstresult[' id ']+ ' name: ' + firstresult[' name ']); } } ); Client.end (); Console.log (' Close MySQL connection ... '); };clientconnectionready (client);
Nodejs connecting MySQL Database