Example of operating mysql database in nodejs, nodejsmysql
Introduction: Following the Hello, World! We can also see other advantages: NodeJS's popularity in the community, and the support of a large number of engineers, it has now introduced a large number of modules.
Content: The following shows the interaction between NodeJS and Mysql.
Now, we need to add the Mysql Module to NodeJS. In this case, the npm (Node package manager) mentioned in the previous chapter plays a role.
Install the Mysql Module in NodeJS:
Copy codeThe Code is as follows:
$ Npm install Mysql
JS script mysqlTest. js
Copy codeThe Code is as follows:
// 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 ();
}
);
Execute scripts
Copy codeThe Code is as follows:
Node mysqlTest. js
The effect is as follows: