Recently in the entry Nodejs, just learned how to use the Nodejs database connection, feel more important, then write essays, simply record
After installing node, we can use the NPM command to install the MySQL module in Nodejs in the root directory of the project.
NPM Install MySQL
Before connecting to the database, first introduce the Nodejs connection to the MySQL module
var mysql = require (' mysql ');
Like the way PHP connects to MySQL, write the connection code
// use Nodejs to process the MySQL module, create a connection with MySQL using the Create Join method var conn = mysql.createconnection ({ ' localhost ', // server port User: ' Root ', // database user name password: ', // password : ' Nodejs ', // Specify the port number of the connected database port:3306 // server });
After getting the database information, start to perform the database connection
Conn.connect ();
Next is a simple database of additions and deletions to check
The data table for the database is the same.
Manipulate data in a data table
// queries the user named Zhang San in the user table and prints the result function(err, result) { ifthrow Err; Console.log (result);})
Output results in console:
// added A new user function(err, result) { ifthrow) to the User data table err; Console.log (result);})
Output results in console:
The database displays:
As you can see, there is one more user named Lisi in the database, but no ID
To delete the data:
// Delete delete user function(err, result) { ifthrow) in user table named Xiaoming err; Console.log (result);})
On the console output:
The display of the database:
In the datasheet, the user named Xiaoming has been deleted
// Modify The data to modify the user information named Lisi conn.query (' Update user set id= ' 3 ' where username= ' Lisi ',function( Err,result) { if (err) {throw err}; Console.log ("Modify data Success");})
On the console output:
Display in the database:
In the user table we can see that the user named Lisi, the new field with an ID added
The above steps, is nodejs to MySQL in the data table information, the simple operation of adding and removing the search and change, slowly in-depth learning, a lot of actual combat hope to improve the ability to process data, hope to harvest more, but also hope to see the article of the children's shoes, can be a lot of advice
Nodejs connect MySQL and make simple additions and deletions to check and change