SQLite in memory example with INSERT and SELECT



examples/sqlite/in-memory-example/Cargo.toml
[package]
name = "in-memory-example"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
sqlite = "0.32.0"

examples/sqlite/in-memory-example/src/main.rs
use sqlite::{Connection, State};

fn main() {
    let connection = sqlite::open(":memory:").unwrap();
    connection
        .execute("CREATE TABLE users (name TEXT, age INTEGER);")
        .unwrap();
    connection
        .execute("INSERT INTO users VALUES ('Alice', 42);")
        .unwrap();
    connection
        .execute("INSERT INTO users VALUES ('Bob', 23);")
        .unwrap();

    fetch(&connection, "SELECT * FROM users");
    println!("---------------------");
    fetch(&connection, "SELECT * FROM users WHERE age > 30");
}

fn fetch(connection: &Connection, query: &str) {
    let mut statement = connection.prepare(query).unwrap();

    while let Ok(State::Row) = statement.next() {
        let name: String = statement.read("name").unwrap();
        let age: i64 = statement.read("age").unwrap();
        //let name = statement.read::<String, _>("name").unwrap();
        //let age = statement.read::<u32, _>("age").unwrap();
        println!("name = {name:6} age = {age}");
    }
}

name = Alice  age = 42
name = Bob    age = 23
---------------------
name = Alice  age = 42