为了在数据库中编写项目向量,我的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字段)。