[Node.js] 使用 mysql2 模組,連線到 MySQL 資料庫

[Node.js] 使用 mysql2 模組,連線到 MySQL 資料庫

這一篇其實只是因為在找 MySQL 連線的問題,

記錄一下用到的 Node.js mysql2 用法~

 

執行 node 之後,先引入 mysql2 模組:

const mysql = require('mysql2');

 

執行  createConnection() 函式,來連到 MySQL 資料庫。

如果資料不對 (不管是主機位址不對、帳號密碼錯誤、或是 SSL 未正確設定等等),

這函式都會丟出一個例外 (exception):

const connection = mysql.createConnection({host:"192.168.0.5", user: "root", password: "myPassword@1", ssl: {rejectUnauthorized: true}})

 

如果連線成功的話,就可以用  query() 這個函式來執行查詢指令了:

connection.query("show databases", function(err, results, fields) {console.log(err); console.log(results);})

 

參考資料:mysql2 – npm

(本頁面已被瀏覽過 1,055 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料