Skip to content

29 · Database

DDL and Insertion

Create tables with db.execute and insert rows, counting the affected ones.

On this page

db.execute(sql) works for both DDL (CREATE TABLE, DROP TABLE) and DML that returns no rows (INSERT, UPDATE, DELETE). It returns Result<int, DbError> — unwrap or handle the error, and on success the int is the number of affected rows, useful for confirming the operation produced the expected effect.

For multi-line DDL, use the block literal ```sql ... ``` — the same as a heredoc string, but with SQL syntax highlighting in the editor.

Creates the products table, inserts three rows, and verifies the return of execute.

02-create-and-insert.zolo
// Feature: Database — `db.execute(sql)` for DDL and DML

// Syntax: `db.execute("...").unwrap()` — returns Result<int, DbError>;

//         the int is the number of affected rows.

// When to use: create schema, populate tables, any SQL that does not

// return rows.


use std::database::Database

let db = Database.open("sqlite://:memory:").unwrap()
defer db.close()

db.execute(```sql
  CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    price REAL
  )
```).unwrap()

let inserted = db.execute("INSERT INTO products (id, name, price) VALUES (1, 'Widget', 9.99)").unwrap()
print("inserted: {inserted}")
// expected: inserted: 1


db.execute(sql"INSERT INTO products (id, name, price) VALUES (2, 'Gadget', 19.99)").unwrap()
db.execute(sql"INSERT INTO products (id, name, price) VALUES (3, 'Doohickey', 4.99)").unwrap()
print("3 products inserted")
// expected: 3 products inserted

Requires the Zolo CLI/host — open in the playground or run locally.

Challenge

Add a fourth product and then run an UPDATE that changes the price of all items with price < 10. How many rows were affected?

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br