具體的安裝MySQL省略。。。node
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your password'; ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your password'; 複製代碼
使用mysql模塊或者node.js的orm時須要在mysql命令行中配置一下密碼,才能夠正常啓動node.js鏈接mysql
1.安裝mysql引擎sql
npm install mysql --save
複製代碼
mysql模塊是node.js操做MySQL的驅動(引擎),能夠在node.js環境下對MySQL數據庫進行建表,增、刪、改、查等操做。數據庫
2.建立MySQL數據庫npm
CREATE DATABASE login_test DEFAULT CHARSET utf8;
複製代碼
const mysql = require('mysql'); 複製代碼
connection
實例使用createConnection
方法,該方法接受一個OBject參數,提供鏈接數據庫的主機,用戶名,密碼,數據庫名,建立一個connection
實例鏈接對象。數組
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); 複製代碼
調用connection中的connect方法鏈接數據庫,該方法接受一個含有err的函數,提供了錯誤處理辦法。bash
connection.connect(function (err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); 複製代碼
end
和destroy
兩種方法,區別是destroy會立刻中止數據庫鏈接,而end
方法會在處理完數據庫請求後中止鏈接。connection.end(function (err) { if (err) { return console.log('error:' + err.message); } console.log('Close the database connection.'); }); 複製代碼
完整的數據庫鏈接markdown
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); connection.connect(function (err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); connection.end(function (err) { if (err) { return console.log('error:' + err.message); } console.log('Close the database connection.'); }); 複製代碼
經過connection
的createPool
方法能夠建立鏈接池。函數
const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); 複製代碼
這樣將建立一個具備10個鏈接的鏈接池。須要注意的是,鏈接池的建立是惰性的,若是僅僅使用2個鏈接,將僅創立2個鏈接。oop
2.使用鏈接池
首先,鏈接池是這樣的調用順序pool.getConnection() -> connection.query() -> connection.release()
pool.getConnection(function (err, connection) { if (err) throw err; // not connected! // Use the connection connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { // When done with the connection, release it. connection.release(); // Handle error after the release. if (error) throw error; console.log('The solution is: ', results[0].solution); // Don't use the connection here, it has been returned to the pool. }); }); 複製代碼
使用完鏈接後,能夠經過connection.release
方法釋放鏈接,能夠被其餘請求使用。
使用connection.destroy
方法,能夠摧毀當前鏈接,鏈接池能夠在須要時,建立一個新的鏈接。
使用end
方法能夠關閉鏈接池的全部鏈接
pool.end(function (err) { // all connections in the pool have ended }); 複製代碼
須要注意的是,執行pool.end
會調用每個鏈接的connction.end
方法,已經在event loop
執行棧中的任務會繼續執行,未進入的將不會執行。
完整例子
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); pool.getConnection(function (err, connection) { if (err) throw err; // not connected! // Use the connection connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { // When done with the connection, release it. connection.release(); // Handle error after the release. if (error) throw error; console.log('The solution is: ', results[0].solution); // Don't use the connection here, it has been returned to the pool. }); }); setTimeout(function () { pool.end(function (err) { // all connections in the pool have ended }); }, 1000) 複製代碼
query
方法mysql模塊提供了一個query
方法,能夠經過實例化後的Connection
,Pool
,PoolNamespace
調用。query
方法有兩種使用方法:
.query(sqlString, callback)
.query(sqlString, values, callback)
values爲sql語句中佔位符的替換變量,須要以Array
的形式提供,若是爲多個變量則須要以Array
中嵌套Array
的方式使用。(在MySQL寫入中有具體例子)
callback回調函數有三個參數:
error:錯誤信息
results:查詢結果
fields:結果字段信息
使用mysql建立表
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); // connect to the MySQL server connection.connect(function (err) { if (err) { return console.error('error: ' + err.message); } }); let createTodos = `create table if not exists user_table( id int primary key AUTO_INCREMENT, name varchar(255) NOT NULL, password varchar(255) NOT NULL, email varchar(255) DEFAULT '', create_time datetime NOT NULL, update_time datetime DEFAULT NOW() ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;`; connection.query(createTodos, function (err, results, fields) { if (err) { console.log(err.message); } }); connection.end(function (err) { if (err) { return console.log(err.message); } }); 複製代碼
這裏使用了一個簡單的user表,若是實際項目中,應該將Profile
和Authorization
分離
MySQL命令行中輸入 use login_test;
後show tables;
查看建好的數據表
單行寫入
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const sql = `INSERT INTO user_table (name,password,create_time) VALUES ('test','123','2019-08-25 00:00:00'); ` pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
MySQL命令行查看結果select * from user_table;
使用佔位符?
動態寫入
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const values = ['test', '123', '2019-08-25 00:00:00'] const sql = `INSERT INTO user_table (name,password,create_time) VALUES ( ? , ? , ? ); ` pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, values, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
這裏經過query
語句的第二種使用方法(三個參數)來實現動態生成SQL語句而後插入。
一次插入多行
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const values = [[ ['test1', '1', '2019-08-25 00:00:00'], ['test2', '2', '2019-08-25 00:00:00'], ['test3', '3', '2019-08-25 00:00:00'] ]] const sql = `INSERT INTO user_table (name,password,create_time) VALUES ? `; pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, values, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
將SQL語句中(?,?,?)
換成?
,values
換成三層嵌套的數組形式。
簡單查詢
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const sql = `SELECT * from user_table`; pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
傳值查詢
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const values = `test`; const sql = `SELECT * from user_table WHERE name=?`; pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, values, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
注意:這個?佔位符號的寫法與escape
方法執行邏輯是一致的,一樣能夠抵禦簡單SQL注入。
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const values = ['test_pass', 'test1']; const sql = `UPDATE user_table SET password=? WHERE name=?`; pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, values, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼
依然使用?
佔位符還有value的Array
參數。
刪除單個查詢結果
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: 'password', database: 'login_test' }); const values = ['test', '4']; const sql = `DELETE from user_table WHERE name=? AND id=?`; pool.getConnection(function (err, connection) { if (err) throw err; connection.query(sql, values, function (error, results, fields) { connection.release(); if (error) throw error; console.log(results) }); }); 複製代碼