首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

Node.js 連接 MySQL 完整教學:從安裝到 db-mysql 實戰

     編輯:MySQL 綜合教學

本文記錄在 macOS 上安裝 MySQL、圖形化工具 Sequel Pro,並使用 Node.js db-mysql 套件連線資料庫的完整流程,包含常見編譯錯誤 Unable to load shared library 的解決方案。

一、環境準備

  1. 安裝 MySQL:官網下載 DMG 安裝包,安裝後可在「系統偏好設定」啟動/停止服務。預設 root 無密碼。
  2. 安裝 Sequel Pro:官網下載,方便圖形化管理、建立測試資料表。
  3. 建立測試資料:建立 test 資料庫與 user 表,插入幾筆資料供後續讀取。

二、Node.js 專案初始化與套件安裝

mkdir ReadMysql && cd ReadMysql
npm init -y
export MYSQL_CONFIG=/usr/local/mysql/bin/mysql_config   # 關鍵:指定 mysql_config 路徑
npm install db-mysql

💡 MYSQL_CONFIG 環境變數必須在 npm install 前設定,否則編譯階段找不到 MySQL 客戶端庫會報錯。

三、連線測試程式碼

// read.js
var mysql = require('db-mysql');

new mysql.Database({
    hostname: 'localhost',
    user: 'root',
    password: 'password',   // Sequel Pro 設定的 root 密碼
    database: 'test'
}).connect(function (err) {
    if (err) return console.log('CONNECTION error:', err);

    this.query()
        .select('*')
        .from('user')
        .execute(function (err, rows, cols) {
            if (err) return console.log('ERROR:', err);
            rows.forEach(function (row) {
                console.log(row.name);
            });
        });
});

四、常見錯誤與解決

錯誤:Error: Unable to load shared library ... mysql_bindings.node

原因:動態連結器找不到 MySQL client library(libmysqlclient.dylib)。

解決:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
# 或永久生效寫入 ~/.bash_profile / ~/.zshrc
echo 'export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/' >> ~/.zshrc
source ~/.zshrc

再次執行 node read.js 即可正常輸出資料。

五、補充:主流替代方案

db-mysql 專案已停止維護,生產環境建議使用:

  • mysql2:npm install mysql2,效能更好、支援 Promise/Prepared Statement。
  • Sequelize / TypeORM / Prisma:ORM 框架,適合中大型專案。

六、快速驗證 mysql2 寫法

const mysql = require('mysql2/promise');
(async () => {
  const conn = await mysql.createConnection({host:'localhost', user:'root', password:'password', database:'test'});
  const [rows] = await conn.execute('SELECT name FROM user');
  console.log(rows);
  await conn.end();
})();

掌握 Node.js 連接 MySQL 的完整鏈路,能快速排除環境配置坑,專注於業務開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved