Install MySQL module into Nodejs
JS Code
Copy Code code as follows:
JS Script Mysqltest.js
JS Code
Copy Code code as follows:
Mysqltest.js
Loading MySQL Module
var Client = require (' MySQL '). Client,
Client = new Client (),
The name of the database to create
Test_database = ' Nodejs_mysql_test ',
The name of the table to create
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 would be emitted as ' error '
Events by the client
Client.query (' use ' +test_database);
Client.query (
' CREATE TABLE ' +test_table+
' (ID INT (one) auto_increment, ' +
' Title VARCHAR (255), ' +
' Text text, ' +
' Created DATETIME, ' +
' PRIMARY KEY (ID)] '
);
Client.query (
' INSERT into ' +test_table+ ' +
' SET title =?, Text =?, created =? ',
[' Super cool ', ' It's a nice text ', ' 2010-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 ', ' 2010-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 script
JS Code
Copy Code code as follows:
root@sammor-desktop:/var/iapps/nodejs/work# node Mysqltest.js