Rust: rusqlite の使い方


こちらのサンプルを改造してみました。
Crate rusqlite

フォルダー構造

$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    └── debug
Cargo.toml
[package]
name = "sqlite_read"
version = "0.1.0"
edition = "2018"

[dependencies]
rusqlite = "*"
src/main.rs
// --------------------------------------------------------------------
/*
    src/main.rs

                    Jul/23/2020
*/
// --------------------------------------------------------------------
use rusqlite::{params, Connection, Result};

#[derive(Debug)]
struct City {
    id: String,
    name: String,
    population: i32,
}

fn main() -> Result<()> {
    eprintln! ("*** start ***");

    let conn = Connection::open_in_memory()?;


    conn.execute(
        "CREATE TABLE person (
                  id              VARCHAR(10) PRIMARY KEY,
                  name          TEXT NOT NULL,
                  population      INTEGER
                  )",
        params![],
    )?;


    conn.execute(
        "INSERT INTO person (id,name, population) VALUES (?1, ?2, $3)",
        params!["t0711".to_string(),"郡山".to_string(), 18954],
    )?;

    conn.execute(
        "INSERT INTO person (id, name, population) VALUES (?1, ?2, $3)",
        params!["t0712".to_string(),"会津若松".to_string(), 83576],
    )?;

    conn.execute(
        "INSERT INTO person (id, name, population) VALUES (?1, ?2, $3)",
        params!["t0713".to_string(),"白河".to_string(), 51769],
    )?;

    let mut stmt = conn.prepare("SELECT id, name, population FROM person")?;
    let city_iter = stmt.query_map(params![], |row| {
        Ok(City {
            id: row.get(0)?,
            name: row.get(1)?,
            population: row.get(2)?,
        })
    })?;

    for city in city_iter {
        println!("{:?}", city.unwrap());
    }

    eprintln! ("*** end ***");

    Ok(())
}

// --------------------------------------------------------------------

実行結果

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/sqlite_read`
*** start ***
City { id: "t0711", name: "郡山", population: 18954 }
City { id: "t0712", name: "会津若松", population: 83576 }
City { id: "t0713", name: "白河", population: 51769 }
*** end ***