Rust and Sqlite

Add the dependencies

[dependencies]
rusqlite = { version = "0.37.0", features = ["bundled"] }

The bundled part will automatically compile and link an upto date SQLite, without this I got errors such as “LINK : fatal error LNK1181: cannot open input file ‘sqlite3.lib'”, obviously if you have everything installed for SQLite, then you might prefer the non-bundled dependency, so just replace this with.

[dependencies]
rusqlite = "0.37.0"

Create a DB

Now let’s create a database as a file and insert an initial row of data

use rusqlite::Connection;

fn main() {
    let connection = Connection::open("./data.db3").unwrap();
    connection.execute("CREATE TABLE app (id INTEGER PRIMARY KEY, name TEXT NOT NULL", ()).unwrap();
    connection.execute("INSERT INTO app (id, name) VALUES (?, ?)", (1, "Hello")).unwrap();
}

We could also do this in memory using the following

let connection = Connection::open_in_memory().unwrap();

Reading from our DB

We’ll create a simple structure representing the DB created above

#[derive(Debug)]
struct App {
    id: i32,
    name: String,
}

Now to read into this we use the following

let mut statement = connection.prepare("SELECT * FROM app").unwrap();
let app_iter = statement.query_map([], |row| {
  Ok(App {
    id: row.get(0)?,
    name: row.get(1)?,
  })
}).unwrap();

for app in app_iter {
  println!("{:?}", app.unwrap());
}

You’ll also need the following use clause

use rusqlite::fallible_iterator::FallibleIterator;