sqlite.rs (1253B)
1 /* 2 use rusqlite::NO_PARAMS; 3 use rusqlite::{Connection, Result}; 4 use std::collections::HashMap; 5 6 #[derive(Debug)] 7 struct Cat { 8 name: String, 9 color: String, 10 } 11 12 fn main() -> Result<()> { 13 let conn = Connection::open("cats.db")?; 14 15 let mut cat_colors = HashMap::new(); 16 cat_colors.insert(String::from("Blue"), vec!["Tigger", "Sammy"]); 17 cat_colors.insert(String::from("Black"), vec!["Oreo", "Biscuit"]); 18 19 for (color, catnames) in &cat_colors { 20 conn.execute( 21 "INSERT INTO cat_colors (name) values (?1)", 22 &[&color.to_string()], 23 )?; 24 let last_id: String = conn.last_insert_rowid().to_string(); 25 26 for cat in catnames { 27 conn.execute( 28 "INSERT INTO cats (name, color_id) values (?1, ?2)", 29 &[&cat.to_string(), &last_id], 30 )?; 31 } 32 } 33 let mut stmt = conn.prepare( 34 "SELECT c.name, cc.name from cats c 35 INNER JOIN cat_colors cc 36 ON cc.id = c.color_id;", 37 )?; 38 39 let cats = stmt.query_map(NO_PARAMS, |row| { 40 Ok(Cat { 41 name: row.get(0)?, 42 color: row.get(1)?, 43 }) 44 })?; 45 46 for cat in cats { 47 println!("Found cat {:?}", cat); 48 } 49 50 Ok(()) 51 } 52 */