Using Node for web page development is basically connecting to the non-relational database mongodb. Here I tried to connect to the mysql database first, because mongodb is too unfamiliar with mysql and wants to quickly come out of the page, so I chose mysql that is relatively familiar.
1. Install mysql
Download MySQL:MySQL Downloads and install it. After installation, you will be guided to configure the database, set the root password, and create ordinary users and passwords.
2. Install Node-mysql
Install the mysql package through npm, and use it to facilitate and quickly call functions to connect to the mysql database. Enter the project folder and execute npm install mysql --save.
After installation, the mysql directory will be generated in the node_modules directory of the project folder.
3. View readme documentation
Enter the mysql directory and view the README document. This step is very important. Don’t use Baidu Google search everywhere, because due to the different versions, the answer you get may not allow you to successfully connect to the database. After all, Node is developing so fast.
If you read the README document carefully, you don’t need to read the next steps anymore to avoid misleading you due to inconsistent versions.
4. Connect to mysql database
Enter the project document, create a new example, and write the following code:
var mysql = require('mysql'); var connection = ({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); (); ('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; ('The solution is: ', rows[0].solution); }); ();
Connection basic parameters
- host host name, localhost represents local
- user Mysql user
- password password
- database connected to the database
()Connect the database
()Execute SQL statement
() Close the connection.
Then execute the program through node to make sure that you have started the Mysql service before execution.
5. Add, delete, modify and check
Using a database is nothing more than adding, deleting, modifying and checking. The following examples may be helpful to you.
var mysql = require('mysql'); var connection = ({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); (); // Add records('insert into test (username ,password) values ("lupeng" , "123456")'); // Delete records('delete from test where username = "lupeng"'); // Modify records('update test set username = "pengloo53" where username = "lupeng"'); // Query the record("select * from test" , function selectTable(err, rows, fields){ if (err){ throw err; } if (rows){ for(var i = 0 ; i < ; i++){ ("%d\t%s\t%s", rows[i].id,rows[i].username,rows[i].password); } } }); ();
At this point, the initial connection to the Mysql database has come to an end, and you can play your own way in the Node project.
I hope everyone will continue to pay attention.