Skip to main content

Insert Data into a Multi-Index Table

Overview

This guide provides instructions for inserting data into a multi-index table.

Prerequisites

Steps

Complete the following steps to insert a user object in the testtab multi-index table:

1. Verify If the User Already Exists

Use the multi-index table iterator to find out if the user object already exists. The targeted user is searched based on its account name.

contract.cpp
[[sysio::action]] void multi_index_example::set(name user) {
// check if the user already exists
auto itr = testtab.find(user.value);
}

2. Insert the User If Not Found in Table

Use the emplace method to make the insertion if the user object is not already in the multi-index table. Otherwise print an informational message.

contract.cpp
[[sysio::action]] void multi_index_example::set(name user) {
// check if the user already exists
auto itr = testtab.find(user.value);
if (itr == testtab.end()) {
testtab.emplace(_self, [&](auto& u) {
u.test_primary = user;
u.secondary = "second"_n;
u.datum = 0;
});
} else {
printf("User already exists.");
}
}
info

A full example project demonstrating the instantiation and usage of multi-index tables can be found in the multi_index example project.

Reference

Relevant classes and methods:

Next Steps