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 ***
Author And Source
この問題について(Rust: rusqlite の使い方), 我々は、より多くの情報をここで見つけました https://qiita.com/ekzemplaro/items/218eef74506e09bb03f3著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .