ERROR 1615 (HY000): Prepared statement needs to be re-prepared
場景:合服腳本執行、DDL 操作後、大量表結構變更後隨機出現。
MySQL Prepared Statement 緩存機制:
PREPARE stmt FROM ... 時,解析 SQL、綁定表結構元數據 (列、索引、統計信息) 存入緩存。EXECUTE stmt 直接使用緩存計劃。EXECUTE 時,檢測到版本不匹配 → 拋出 ERROR 1615,要求重新 PREPARE。本質:表定義緩存 (Table Definition Cache) 滿/淘汰導致元數據版本檢查失效,或高併發 DDL 導致版本號快速增長。
| 參數 | 默認值 | 建議調大值 | 作用 |
|---|---|---|---|
table_open_cache | 4000 (5.7) / 2000 (5.6) | 16384+ | 打開表實例緩存 (含數據文件句柄) |
table_definition_cache | 1400 (5.7) / 400 (5.6) | 16384+ | 表結構定義 (.frm/數據字典) 緩存,**核心影響 Prepared Statement 元數據版本** |
SET GLOBAL table_open_cache = 16384;
SET GLOBAL table_definition_cache = 16384;
[mysqld]
table_open_cache = 16384
table_definition_cache = 16384
-- 監控緩存命中率
SHOW GLOBAL STATUS LIKE 'Open_table_definitions';
SHOW GLOBAL STATUS LIKE 'Opened_table_definitions';
-- Opened_table_definitions / Uptime 過高 ( > 10/秒 ) 說明緩存不足
-- 監控 Prepared Statement 重準備
SHOW GLOBAL STATUS LIKE 'Com_stmt_reprepare';
-- 非零即發生 1615 錯誤
open_files_limit (建議 65535+)。pt-online-schema-change/gh-ost 在線變更,減少元數據版本衝突。ERROR 1615 / SQLSTATE HY000 → 重新 PREPARE → EXECUTE,避免業務報錯。table_definition_cache 需 ≥ 總表數 * 1.5。ERROR 1615 核心是**表定義緩存不足導致 Prepared Statement 元數據失效**。調大 table_definition_cache (核心) 與 table_open_cache 至業務表數 1.5-2 倍,配合 open_files_limit 放寬,並監控 Com_stmt_reprepare 歸零,可徹底治愈。應用層增加重試邏輯作為最後防線。