LoginSignup
0
0

More than 3 years have passed since last update.

Rust: sqlite3 のデータを読む (Read)

Posted at

フォルダー構造

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

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

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

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

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

    let args: Vec<_> = env::args().collect();

    let file_sqlite3 = &args[1];

    eprintln!("{}",file_sqlite3);

    let conn = Connection::open(file_sqlite3).unwrap();

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

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

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

    Ok(())
}

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

実行

$ cargo run /var/tmp/sqlite3/cities.db
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
     Running `target/debug/sqlite3_read /var/tmp/sqlite3/cities.db`
*** start ***
/var/tmp/sqlite3/cities.db
City { id: "t0711", name: "郡山", population: 38415, date_mod: "1956-5-15" }
City { id: "t0712", name: "会津若松", population: 57926, date_mod: "1956-6-8" }
City { id: "t0713", name: "白河", population: 98123, date_mod: "1956-8-17" }
City { id: "t0714", name: "福島", population: 63259, date_mod: "1956-1-21" }
City { id: "t0715", name: "喜多方", population: 21748, date_mod: "1956-9-12" }
City { id: "t0716", name: "二本松", population: 51924, date_mod: "1956-7-5" }
City { id: "t0717", name: "いわき", population: 97125, date_mod: "1956-9-12" }
City { id: "t0718", name: "相馬", population: 63219, date_mod: "1956-3-22" }
City { id: "t0719", name: "須賀川", population: 25781, date_mod: "1956-11-30" }
*** end ***
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0