1. Install MySQL
Download the Mysql:mysql Downloads and install it. After installation, you will be guided to configure the database, set the root password and create a regular user and password.
2. Installing Node-mysql
Install MySQL's software package via NPM, which makes it easy to quickly call functions to connect to MySQL database. Go to the project folder and execute NPM install MySQL--save.
After installation, the MySQL directory will be generated under the Node_modules directory of the project folder.
3. View the Readme document
Enter the MySQL directory, view the Readme document, this step is very important, do not go around Baidu Google search how to use, because the version of the different, perhaps you get the answer does not make you successfully connected to the database. After all, node has grown so fast.
If you read the Readme document carefully, the next steps will not have to be looked at, to avoid being misled by version inconsistencies.
4. Connect to MySQL Database
Enter the project document, create a new testmysql.js example, and write the following code:
?
1234567891011121314151617 |
var mysql = require(
‘mysql‘
);
var
connection = mysql.createConnection({
host :
‘localhost‘
,
user
:
‘me‘
,
password :
‘secret‘
,
database :
‘my_db‘
});
connection
.
connect
();
connection
.query(
‘SELECT 1 + 1 AS solution‘
,
function
(err,
rows
, fields) {
if (err) throw err;
console.log(
‘The solution is: ‘
,
rows
[0].solution);
});
connection
.
end
();
|
Connection Basic Parameters
- Host hostname, localhost on behalf of local
- User MySQL Users
- Password Password
- Database connected Databases
Client.connect () Connection database
Client.query () Execute SQL statement
Client.end () closes the connection.
Then execute the program via node Testmysql.js to make sure that you have started the MySQL service before executing.
5. Adding and deleting changes
Use the database without adding or removing changes, the following example may be of some help to you.
?
1234567891011121314151617181920212223242526272829303132 |
var mysql = require(
‘mysql‘
);
var
connection = mysql.createConnection({
host :
‘localhost‘
,
user
:
‘me‘
,
password :
‘secret‘
,
database :
‘my_db‘
}); connection
.
connect
();
// 增加记录
client.query(
‘insert into test (username ,password) values ("lupeng" , "123456")‘
);
// 删除记录
client.query(
‘delete from test where username = "lupeng"‘
);
// 修改记录
client.query(
‘update test set username = "pengloo53" where username = "lupeng"‘
);
// 查询记录
client.query(
"select * from test" ,
function selectTable(err,
rows
, fields){
if (err){
throw err;
}
if (
rows
){
for
(var i = 0 ; i <
rows
.length ; i++){
console.log(
"%d\t%s\t%s"
,
rows
[i].id,
rows
[i].username,
rows
[i].
password
);
}
}
});
connection
.
end
();
|
Here, the initial connection to the MySQL database is over, and then it can be played on the node project itself.
Initial use of node to connect to MySQL database