Home  >  Article  >  Web Front-end  >  Example of operating mysql database in nodejs_node.js

Example of operating mysql database in nodejs_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:291655browse

Introduction: Following the previous Hello, World of NodeJS! We can also see other strengths. With the popularity of the NodeJS community and the support of a large number of engineers, a large number of modules have been introduced one after another.

Content: The following demonstrates the interaction between NodeJS and Mysql.

At this time, you need to add the Mysql Module to NodeJS. At this time, the npm (Node package manager) mentioned in the previous chapter comes into play.

Install Mysql Module into NodeJS:

Copy code The code is as follows:

$npm install Mysql

JS script mysqlTest.js
Copy code The code is as follows:

// mysqlTest.js
//Load mysql Module
var Client = require('mysql').Client,
client = new Client(),

//The name of the database to be created
TEST_DATABASE = ‘nodejs_mysql_test’,
//Table name to be created
TEST_TABLE = ‘test’;

//Username
client.user = ‘root’;
//Password
client.password = ‘root’;
//Create 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', '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
Copy code The code is as follows:

node mysqlTest.js

The effect is as follows:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn