Interaction between NodeJS and Mysql

Source: Internet
Author: User

Install the Mysql Module in NodeJS

Js Code
$ Npm install Mysql
JS script mysqlTest. js

Js Code

// MysqlTest. js
// Load the mysql Module
Var Client = require ('mysql'). Client,
Client = new Client (),

// Name of the database to be created
TEST_DATABASE = 'nodejs _ mysql_test ',
// Name of the table to be created
TEST_TABLE = 'test ';
 
// User Name
Client. user = 'root ';
// Password
Client. password = 'root ';
// Create a connection
Client. connect ();
 
Client. query ('create database' + TEST_DATABASE, function (err ){
If (err & err. number! = Client. ERROR_DB_CREATE_EXISTS ){
Throw err;
}
});
 
// If no callback is provided, any errors will be emitted as ''error''
// Events by the client
Client. query ('use' + TEST_DATABASE );
Client. query (
'Create table' + TEST_TABLE +
'(Id INT (11) AUTO_INCREMENT,' +
'Title VARCHAR (255), '+
'Text text, '+
'Created DATETIME, '+
'Primary KEY (id ))'
);
 
Client. query (
'Insert INTO '+ TEST_TABLE + ''+
'Set title = ?, Text = ?, Created =? ',
['Super cool ', 'This is a nice text', '2017-08-16 10:00:23']
);
 
Var query = client. query (
'Insert INTO '+ TEST_TABLE + ''+
'Set title = ?, Text = ?, Created =? ',
['Another entry ', 'because 2 entries make a better test', '2017-08-16 12:42:15']
);
 
Client. query (
'Select * from' + TEST_TABLE,
Function selectCb (err, results, fields ){
If (err ){
Throw err;
}
 
Console. log (results );
Console. log (fields );
Client. end ();
}
);

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.