- memory
- open
- execute
- INSERT
- SELECT
SQLite in memory example with INSERT and SELECT
- In this example we use an in-memory database.
- That's useful for the examples and it can be also useful if we have a lot of data on the disk that we would like analyze using SQL statements but we don't need to store the data in a database.
- In general you won't have values embedded in the SQL statements, but in this first example we use that for simplicity.
examples/sqlite/in-memory-example/Cargo.toml
[package] name = "in-memory-example" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] sqlite = "0.32.0"
examples/sqlite/in-memory-example/src/main.rs
use sqlite::{Connection, State}; fn main() { let connection = sqlite::open(":memory:").unwrap(); connection .execute("CREATE TABLE users (name TEXT, age INTEGER);") .unwrap(); connection .execute("INSERT INTO users VALUES ('Alice', 42);") .unwrap(); connection .execute("INSERT INTO users VALUES ('Bob', 23);") .unwrap(); fetch(&connection, "SELECT * FROM users"); println!("---------------------"); fetch(&connection, "SELECT * FROM users WHERE age > 30"); } fn fetch(connection: &Connection, query: &str) { let mut statement = connection.prepare(query).unwrap(); while let Ok(State::Row) = statement.next() { let name: String = statement.read("name").unwrap(); let age: i64 = statement.read("age").unwrap(); //let name = statement.read::<String, _>("name").unwrap(); //let age = statement.read::<u32, _>("age").unwrap(); println!("name = {name:6} age = {age}"); } }
name = Alice age = 42 name = Bob age = 23 --------------------- name = Alice age = 42