Skip to main content

How to insert data into a multi-index table

Overview

This guide provides instructions to insert data into a multi-index table.

Reference

See the following code reference:

Before you begin

Make sure you have the following prerequisites in place:

Procedure

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

1. Verify If The User Already Exists

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

[[eosio::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.

[[eosio::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 | Full example location]] | A full example project demonstrating the instantiation and usage of multi-index table can be found here.

Summary

In conclusion, the above instructions show how to insert data in a multi-index table.

Next Steps