数据库批量插入数据

    为了提高数据库的效率,采用批量插入的方式。

1.InsertEntity

bool DbWriter::InsertEntity(const std::vector<std::shared_ptr<IDbTable>>& entities)
{
    if (entities.size() == 0)
        return true;
    bool flag = BulkInsert(entities, 0, (int)entities.size());
    if (flag)
    {
        GraLOGI(_logger, "Insert Entity success.");
    }
    else
    {
        GraLOGE(_logger, "Insert Entity failed!");
        return false;
    }
    return flag;
}

2.BulkInsert

bool DbWriter::BulkInsert(const std::vector<std::shared_ptr<IDbTable>>& entities, int begin, int end)
{
    if (entities.size() == 0)
        return true;

    int i = 0;
    int bulkSize = 2000;
    int count = static_cast<int>(entities.size());
    while (i < count)
    {
        int end = i + bulkSize;
        if (end > count)
            end = count;

        bool flag = ExecuteInsert(entities, i, end);
        if (!flag)
            return false;
        i = end;
    }
    return true;
}

3.ExecuteInsert

bool DbWriter::ExecuteInsert(const std::vector<std::shared_ptr<IDbTable>>& entities, int begin, int end)
{
    try
    {
        if (!_inTransaction)
        {
            GraLOGE(_logger, "Write not in Transaction!");
            return false;
        }
        std::string sqlCommand = CreateCmdString(entities, begin, end);
        if (sqlCommand.empty())
        {
            return false;
        }

        char *zErrMsg = 0;
        int res = sqlite3_exec(_connectionPtr.get(), sqlCommand.c_str(), 0, 0, &zErrMsg);
        if (res != SQLITE_OK) {

            GraLOGE(_logger, "ExecuteInsert failed! ");
            GraLOGE(_logger, zErrMsg);
            sqlite3_free(zErrMsg);
            return false;
        }
        return true;
    }
    catch (const std::exception&)
    {
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值