首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL C API 輕量級 C++ 封裝:結構化查詢與結果綁定

     編輯:MySQL 資料庫相關知識

設計目標

為簡化 C/C++ 操作 MySQL 預處理語句,封裝 `MYSQL_STMT` 相關 API,支援參數綁定、結果集綁定、異常拋出,維護 C 結構體與資料表欄位的映射關係。

核心類別結構

struct mysql_parm {
    std::string host, user, password, database, unixsock;
};

class DBMysql;  // 連線管理類(略)

class DBSTMT {
    DBSTMT(const DBSTMT&);             // 禁用拷貝
    DBSTMT& operator=(const DBSTMT&);  // 禁用賦值
    MYSQL_STMT* stmt_;

public:
    DBSTMT(const char* query, DBMysql& mysql);  // 建立預處理語句

    void execute() {                          // 無參數執行
        if (mysql_stmt_execute(stmt_))
            throw mysql_stmt_error(stmt_);
    }

    void execute(MYSQL_BIND* bind) {          // 綁定結果集執行
        if (mysql_stmt_execute(stmt_))
            throw mysql_stmt_error(stmt_);
        if (mysql_stmt_bind_result(stmt_, bind))
            throw mysql_stmt_error(stmt_);
        if (mysql_stmt_store_result(stmt_))
            throw mysql_stmt_error(stmt_);
    }
    // 可擴展:bind_param、fetch 等封裝
};

使用場景

  • 高頻參數化查詢(防注入、效能優化)
  • 需將結果集直接映射到 C 結構體數組
  • 嵌入式/高併發場景下減少 API 呼叫複雜度

擴展建議

  1. 補全 `DBMysql` 類:連線池、重連邏輯、事務控制
  2. 增加 `bind_param` 封裝,支援輸入參數批次綁定
  3. 實作 RAII 風格資源管理,確保 `stmt_` 在異常時正確關閉
  4. 提供 `fetch_row()` 迭代器介面,簡化業務代碼
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved