Created
September 15, 2020 05:16
-
-
Save kuc-arc-f/a9d18b7619d4d685a21d86772e20df05 to your computer and use it in GitHub Desktop.
Rust, rusqlite で、sqlite3を操作する例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[dependencies] | |
rusqlite = "0.24.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rusqlite::{params, Connection, Result}; | |
#[derive(Debug)] | |
struct Person { | |
id: i32, | |
name: String, | |
data: Option<Vec<u8>>, | |
} | |
// | |
fn main() -> Result<()> { | |
let file_sqlite3: String = "db1.db".to_string(); | |
let conn = Connection::open(file_sqlite3).unwrap(); | |
let me = Person { | |
id: 0, | |
name: "Steven".to_string(), | |
data: None, | |
}; | |
conn.execute( | |
"INSERT INTO person (name, data) VALUES (?1, ?2)", | |
params![me.name, me.data], | |
)?; | |
let mut stmt = conn.prepare("SELECT id, name, data FROM person")?; | |
let person_iter = stmt.query_map(params![], |row| { | |
Ok(Person { | |
id: row.get(0)?, | |
name: row.get(1)?, | |
data: row.get(2)?, | |
}) | |
})?; | |
for person in person_iter { | |
println!("Found person {:?}", person.unwrap()); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment