資料庫指令要先分成唯讀查詢、結構變更與資料變更。日常排查先看版本、連線、鎖定、執行計畫與容量;備份檔存在不等於能還原。
動手前:不要把密碼直接接在 -p 後面,避免出現在 shell history 與程序列表。正式備份與還原要確認版本、字元集、GTID、儲存引擎、權限與一致性需求。
登入與基本查詢
互動輸入密碼登入MySQL client
mysql -h db.example.com -P 3306 -u appreader -p-p 後不放密碼,讓 client 提示輸入。
指定資料庫登入MySQL client
mysql -h db.example.com -u appreader -p appdb帳號應採最小權限。
執行單一唯讀查詢MySQL client
mysql -h db.example.com -u appreader -p -e "SELECT VERSION();"輸出可用於版本稽核。
查看資料庫MySQL SQL
SHOW DATABASES;只能看到帳號有權限的資料庫。
查看資料表MySQL SQL
SHOW TABLES FROM appdb;先確認目前 schema。
查看表結構MySQL SQL
SHOW CREATE TABLE appdb.orders\G比 DESCRIBE 更完整,可看到索引與選項。
查看目前連線MySQL SQL
SHOW FULL PROCESSLIST;需要權限才能看其他帳號完整資訊。
查看帳號權限MySQL SQL
SHOW GRANTS FOR CURRENT_USER();確認實際登入帳號,而不是假設角色已啟用。
查看變數MySQL SQL
SHOW VARIABLES LIKE 'max_connections';變更前要了解 global、session 與持久化範圍。
查看執行計畫MySQL SQL
EXPLAIN FORMAT=TREE SELECT * FROM orders WHERE order_no = 'A001';用測試值,避免在文章或工單放真實個資。
mysqldump 備份
備份單一資料庫mysqldump
mysqldump -h db.example.com -u backupuser -p --single-transaction --routines --triggers appdb > appdb.sqlInnoDB 可用 single-transaction;非交易表一致性另處理。
壓縮備份mysqldump/gzip
mysqldump -h db.example.com -u backupuser -p --single-transaction appdb | gzip > appdb.sql.gz記得檢查 pipe 每一段的結束狀態與磁碟空間。
只備份結構mysqldump
mysqldump -h db.example.com -u backupuser -p --no-data appdb > appdb-schema.sql不含資料。
只備份指定資料表mysqldump
mysqldump -h db.example.com -u backupuser -p appdb orders customers > selected-tables.sql外鍵相依與一致時間點要另外評估。
備份所有資料庫mysqldump
mysqldump -h db.example.com -u backupuser -p --all-databases --single-transaction --routines --events > all-databases.sql檔案可能非常大,並包含敏感資料。
顯示 dump 進度線索shell
pv appdb.sql.gz > /dev/nullpv 只能看讀取進度,不代表 SQL 可還原。
計算備份雜湊shell
sha256sum appdb.sql.gz > appdb.sql.gz.sha256用來偵測傳輸或儲存損壞。
驗證與還原
檢查 gzip 是否完整gzip
gzip -t appdb.sql.gz只驗壓縮流,不驗 SQL 語意。
查看 dump 前幾行shell
zcat appdb.sql.gz | head -40確認資料庫版本、建立選項與內容類型。
還原到測試資料庫MySQL client
zcat appdb.sql.gz | mysql -h test-db.example.com -u restoreuser -p appdb_restore先建立隔離測試 schema,勿直接覆蓋正式庫。
執行 SQL 檔MySQL client
mysql -h test-db.example.com -u restoreuser -p appdb_restore < appdb.sql還原帳號權限要精確,完成後立即驗證。
檢查 server 是否回應mysqladmin
mysqladmin -h db.example.com -u monitor -p pingmysqld is alive 只表示 server 回應,不代表應用查詢正常。
查看 server 狀態摘要mysqladmin
mysqladmin -h db.example.com -u monitor -p status搭配監控與 performance_schema 判讀。
怎麼確認有做對
- 每次備份都記錄版本、參數、開始/結束時間、大小與 SHA-256。
- 定期還原到隔離環境,驗證筆數、關鍵查詢、procedure、trigger 與字元。
- 備份帳號只給需要的權限並保護輸出檔。
常見錯誤
- 密碼直接寫在 -p 後或腳本裡。
- 看到 .sql 檔存在就當成備份成功。
- 把 MariaDB 與 MySQL 參數完全混用。
- 未驗版本與 GTID 就直接還原正式庫。
版本與官方文件
參數會隨工具版本與作業系統實作改變。正式環境先用 --help、-h 或系統內建說明確認,再以當版官方文件為準。