Install
This is a Node.js module, install:npm install mysql --save
Connect
Before connecting to databases, make sure MySQL database is turned on.
【注意】:
- 先执行
connect()
,让connection object与数据库建立连接。 - 然后,在对该connection执行
.query(MySQL_Command, callback_func)
1 | var mysql = require('mysql'); |
Disconnect
1 | connection.end(function(err) { |
Escaping query values
Three ways to avoid SQL injection
- mysql.escape()
- connection.escape()
- pool.escape()
?
placeholder
1 | // 1 -connection.escape() |
Creating a Database
1 | connection.query("CREATE DATABASE mydb", function (err, result) { |
Creating a Table
Two ways:
- create database and table simultenously
- first create database, and connect it; then create table with the connection
1 | // approach 1 |
Selecting From a Table
To select data from a table in MySQL, use the SELECT
statement.
1 | var sql = "SELECT * FROM customers WHERE address = 'Park Lane 38'"; |
Wildcard Characters%
: represent zero, one or multiple characters:
1 | var sql = "SELECT * FROM customers WHERE address LIKE 'S%'" |
Insert Into Table
To fill a table in MySQL, use the INSERT INTO
statement.
1 | var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')"; |
Update Table
You can update existing records in a table by using the UPDATE
statement:
1 | var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"; |
Sort the Result
Use the ORDER BY
statement to sort the result in ascending or descending order.
The ORDER BY
keyword sorts the result ascending by default. To sort the result in descending order, use the DESC
keyword.
1 | var sql = "SELECT * FROM customers ORDER BY name DESC"; |
Delete Record
You can delete records from an existing table by using the DELETE FROM
statement:
1 | var sql = "DELETE FROM customers WHERE address = 'Mountain 21'"; |
Limit the Result
You can limit the number of records returned from the query, by using the LIMIT
statement:
1 | var sql = "SELECT * FROM customers LIMIT 5"; |
Join Two or More Tables
Combine rows from two or more tables, based on a related column between them, by using a JOIN
statement.
1 | //users |
1 | // products |
1. Inner join
These two tables can be combined by using users’ favorite_product field and products’ id field.
1 | var sql = "SELECT users.name AS user, products.name AS favorite FROM users JOIN products ON users.favorite_product = products.id"; |
2. Left Join
If you want to return all users, no matter if they have a favorite product or not, use the LEFT JOIN statement:
1 | SELECT users.name AS user, |
3. Right Join
If you want to return all products, and the users who have them as their favorite, even if no user have them as their favorite, use the RIGHT JOIN statement:1
2
3
4SELECT users.name AS user,
products.name AS favorite
FROM users
RIGHT JOIN products ON users.favorite_product = products.id