Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Rust sqlite Basic Example

This is what I'm doing for a basic sqlite call setup.

Create A Table

rust
use rusqlite::Connection;
use rusqlite::Result;

fn main() -> Result<()> {
    let conn = Connection::open("./_sqlite_db_test.db3")?;
    let create_table = "
        CREATE TABLE storage (name TEXT, color TEXT)";
    conn.execute(create_table, ())?;
    Ok(())
}

Insert Data

rust
use rusqlite::Connection;
use rusqlite::Result;

fn main() -> Result<()> {
    let conn = Connection::open("./_sqlite_db_test.db3")?;
    let insert_data = "
        INSERT INTO storage (name, color) VALUES (?1, ?2)";
    conn.execute(insert_data, ("alfa", "red"))?;
    Ok(())
}

Query Data

rust
fn main() -> Result<()> {
    let conn = Connection::open("./_sqlite_db_test.db3")?;
    let mut get_data = conn.prepare("SELECT name, color FROM storage WHERE name = ?1")?;
    let response = get_data.query_map(["alfa"], |row| {
        Ok((row.get::<usize, String>(0), row.get::<usize, String>(1)))
    })?;
    for item in response {
        println!("{}", item.unwrap().0.unwrap());
    }
    Ok(())
}

The sqlite 1 rust crate comes up first in seatch but only has 240K downloads. The rusqlite 2 has 8 million. So, I'm going with that.

Footnotes And References