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 ();
}
);