Skip to main content

Data Insertion

Data insertion is done using the INSERT statement, which is used to write data into an existing table. We have already created a database called "bookshop" and a table called "book" under the database. Now we can write book information into our "book" table.

Insert Single Example

We provide flexible methods for data insertion. You can store the data to be inserted in a map, and we will automatically generate the SQL for data insertion and execute it.

SQL Example

INSERT INTO bookshop.book (
id, name, category, author, public_at,
stock, price
) value (
1, 'Token Economy: How the Web3 reinvents the Internet',
'web3', 'Shermin Voshmgir', 1592120979,
5, 70
)

Builtin Method

Both Python and JavaScript versions of the SDK provide the insert() method for inserting data.

item = {
"id": 1,
"name": "Token Economy: How the Web3 reinvents the Internet",
"category": "web3",
"author": "Shermin Voshmgir",
"public_at": 1592120979,
"stock": 5,
"price": 70
}
db = client.db(mk)
db.insert("bookshop.book", item)

Execute SQL

Of course, if you prefer to write your own SQL for execution, you can directly call the corresponding SDK's SQL execution method with the prepared SQL statement for data insertion.

sql = "INSERT INTO bookshop.book (id, name, category, author, public_at, stock, price) value (1, 'Token Economy: How the Web3 reinvents the Internet', 'web3', 'Shermin Voshmgir', 1592120979, 5, 70)"
db = client.db(mk)
db.sql_exec(sql)

Insert Batch Example

We also provide a method for batch insertion of data. This function helps you concatenate the corresponding information into the format of INSERT INTO... () VALUES(), (),....

SQL Example

INSERT INTO 'bookshop.book' (
id, name, category, author, public_at,
stock, price, abstract
) value (
1, 'Token Economy: How the Web3 reinvents the Internet',
'web3', 'Shermin Voshmgir', 1592120979,
5, 70
),
(
2, 'Mastering Bitcoin', 'btc', 'Andreas M.Antonopoulos',
1418548616, 6, 56
);

Python

Python SDK provides the batch_insert() method for batch data insertion.

items = [{
"id": 1,
"name": "Token Economy: How the Web3 reinvents the Internet",
"category": "web3",
"author": "Shermin Voshmgir",
"public_at": 1592120979,
"stock": 5,
"price": 70,
}, {
"id": 2,
"name": "Token Economy: How the Web3 reinvents the Internet",
"category": "web3",
"author": "Shermin Voshmgir",
"public_at": 1592120979,
"stock": 5,
"price": 70,
}]
db = client.db(mk)
db.batch_insert("bookshop","book", items)