为了在数据库中写入项目 vector ,我的C++代码如下:
void DatabaseManager::insertItems(vector<DbEntry>& items) {
shared_ptr<MySQLConnection> connection = nullptr;
try {
connection = connections_->borrow();
auto statement = shared_ptr<Statement>(connection->sql_connection_->createStatement());
unique_ptr<sql::PreparedStatement> pstmt(connection->sql_connection_->prepareStatement(
"INSERT INTO my_table (a, b, c, d, e) VALUES (?,?,?,?,?)"));
for (auto& item : items) {
pstmt->setInt64(1, item.get_a());
pstmt->setUInt(2, item.get_b());
pstmt->setUInt(3, item.get_c());
pstmt->setInt(4, item.get_d());
pstmt->setString(5, item.get_e());
pstmt->executeUpdate();
unique_ptr<sql::ResultSet> rs(statement->executeQuery("SELECT LAST_INSERT_ID()") );
uint64_t id {0};
if (rs->next()) {
id = rs->getUInt64(1);
}
rs->close();
item.set_id(id);
}
connections_->unborrow(connection);
} catch (SQLException &e) {
//code rollbacks here
}
}
我想使此代码片段更快,但我不知道如何。此处未显示的借用和借用函数从std::deque返回连接。让我们将它们视为“快速”。
此插入执行了很多次(使用不同的值),我想知道是否可以进一步优化该部分。如果是,怎么办?需要SELECT LAST_INSERT_ID,我们需要获取行ID(这是一个AUTO_INCREMENT字段)。
最佳答案
一般来说,调整MySQL插入性能是large topic,没有简单的“一刀切”的答案。
查看代码,我建议尝试使用MySQL多行inserts,这将显着提高性能:INSERT INTO my_table (a, b, c, d, e) VALUES (?,?,?,?,?), (?,?,?,?,?), (?,?,?,?,?), (?,?,?,?,?), (?,?,?,?,?) ...
(一直到max_allowed_packet
,默认为1 MB)
在这种情况下,使用准备好的语句可能很麻烦,因此请使用带有escaped值的常规查询。使用MySQL,常规查询也比准备好的语句快一点。
mysql_insert_id()
将返回插入的第一行的ID,由此您可以计算剩余的ID(生成的ID是顺序的)。
关于c++ - 在C++中优化MySQL插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58981417/