Nodejs connecting MySQL Database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.