1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust: rusqlite の使い方

Last updated at Posted at 2020-07-23

こちらのサンプルを改造してみました。
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 ***
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?