c++ mysql prepare 操作类

本文详细介绍了如何在C++程序中利用MySQL的Prepare语句进行数据库操作,包括连接数据库、预编译SQL语句、绑定参数和执行查询,以及相应的错误处理策略。通过对Prepare语句的运用,可以提高代码的安全性和执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include "PrepareCreator.h"

bool PrepareCreator::prepare(const char* sql) {

    this->_stmt = mysql_stmt_init(this->_connection);
    if (!this->_stmt) {
        this->stmtErrorInfo("mysql_stmt_init");
        return false;
    }

    if (mysql_stmt_prepare(this->_stmt, sql, strlen(sql))) {
        this->stmtErrorInfo("mysql_stmt_prepare");
        return false;
    }

    this->_bindParamCount = static_cast<unsigned short>(mysql_stmt_param_count(this->_stmt));
    if (this->_bindParamCount > 0) {
        if (this->_bindParamArray != nullptr) {
            delete []this->_bindParamArray;
            this->_bindParamArray = nullptr;
        }
        this->_bindParamArray = new MYSQL_BIND[this->_bindParamCount];
        if (!_bindParamArray) {
            this->stmtErrorInfo("new MYSQL_BIND");
            return false;
        }
        memset(this->_bindParamArray, 0, sizeof(MYSQL_BIND)*this->_bindParamCount);
    }
    return true;
}

bool PrepareCreator::validIndex(int index) {
    return index < this->_bindParamCount;
}

bool PrepareCreator::bindInt8(int index, int8_t &value) {
    if (index >= this->_bindParamCount) {
        this->errorInfo("bindInt8 index out!");
        return false;
    }
    this->_bindParamArray[index].buffer_type = MYSQL_TYPE_TINY;
    this->_bindParamArray[index].buffer = &value;
    this->_bindParamArray[index].is_unsigned = false;
    return true;
}

bool PrepareCreator::bindInt32(int index, int &value) {
    if (index >= this->_bindParamCount) {
        this->errorInfo("bindInt32 index out!");
        return false;
    }
    this->_bindParamArray[index].buffer_type = MYSQL_TYPE_LONG;
    this->_bindParamArray[index].buffer &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值