在本教學中,您將學習如何從node.js應用程式連接到MySQL資料庫伺服器。
安裝node.js MySQL驅動程式
有一些選項可以從node.js應用程式與MySQL進行交互。在本教程中,我們將向您展示如何使用名為mysqljs/mysql
的MySQL的node.js驅動程式。
首先,創建一個用於存儲node.js應用程式的檔夾,例如,在F:\worksp\mysql\nodejs\nodejs-connect目錄,並使用npm init
命令創建package.json
檔:
F:\worksp\mysql\nodejs\nodejs-connect> npm init
其次,使用以下命令為MySQL軟體包安裝node.js:
F:\worksp\mysql\nodejs\nodejs-connect> npm install mysql
第三步,在nodejs-connect檔夾內創建connect.js
,用於存儲連接到MySQL資料庫伺服器的代碼。
我們將使用todoapp
資料庫進行演示,因此,先運行以下命令在MySQL資料庫伺服器中創建資料庫:
CREATE DATABASE todoapp DEFAULT CHARSET utf8;
創建資料庫後,就可以從Node.js應用程式連接到MySQL資料庫了。接下來編寫Node.js的相關代碼。
從node.js連接到MySQL資料庫伺服器
首先,使用以下語句導入mysql
模組:
let mysql = require('mysql');
其次,通過調用createConnection()
方法並提供MySQL伺服器上的詳細資訊(如主機,用戶,密碼和數據庫),建立與MySQL資料庫的連接,如下所示:
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'todoapp'
});
在本示例中,我們在本地資料庫服務品上與todoapp
資料庫的連接。
第三步,在連接對象上調用connect()
方法連接到MySQL資料庫伺服器:
connect()
方法接受一個具有err
參數的回調函數,如果發生任何錯誤,它將提供詳細的錯誤。
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
完整的connect.js
程式代碼如下所示 -
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
我們來運行並測試一下connect.js
程式 -
F:\worksp\mysql\nodejs\nodejs-connect>node connect.js
openssl config failed: error:02001003:system library:fopen:No such process
Connected to the MySQL server.
如果看到如上所示的“connected to the MySQL server”的消息,那麼恭喜,您已經從node.js應用程式成功連接到MySQL資料庫伺服器。
假設使用MySQL用戶帳號的密碼有錯,並嘗試連接到數據,您將收到一條錯誤消息:
F:\worksp\mysql\nodejs\nodejs-connect>node connect.js
openssl config failed: error:02001003:system library:fopen:No such process
error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES)
請注意,您在connection
對象上調用的每個方法都按順序排隊和執行。
關閉資料庫連接
要正常關閉資料庫連接,請在connection
對象上調用end()
方法。
end()
方法確保在資料庫連接關閉之前始終執行所有剩餘的查詢。
connection.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
要立即強制連接,可以使用destroy()
方法。 destroy()
方法保證不會再為連接觸發回調或事件。
connection.destroy();
請注意,
destroy()
方法不會像end()
方法那樣採取任何回調參數。
到目前為止,整個connect.js
檔的完整代碼如下 -
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
//connection.destroy();
connection.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
池連接/連接池
node.js模組的MySQL驅動程式為您提供了內置的連接池功能 假設您要創建一個具有5
個連接的連接池:
var pool = mysql.createPool({
connectionLimit: 5,
host: 'localhost',
user: 'root',
password: '',
database: 'todoapp'
});
要從池中獲取連接,可以使用getConnection()
方法:
pool.getConnection(function(err, connection) {
// execute query
// ...
});
要在完成連接後將其連接到池,可以調用connection.release()
。 之後,連接將在池中可用,並可以由其他人再次使用。
pool.getConnection(function(err, connection) {
// execute query
// ...
connnection.release();
});
要關閉連接並將其從池中刪除,請使用connection.destroy()
方法。 如果下次需要,將在池中創建一個新的連接。
請注意,連接池中所建立的連接是懶惰的。例如,如果您使用5
個連接配置連接池,但是同時僅使用2
個連接,則連接池僅創建2
個連接。
要關閉池中的所有連接,請使用pool
對象的end()
方法,如下所示:
pool.end(function(err) {
if (err) {
return console.log(err.message);
}
// close all connections
});
在本教學中,您已經學會了如何從node.js應用程式連接到MySQL資料庫。