rusqlite streamline sql select statement

66 views Asked by At

Building app using rusqlite and many sql (sqlite) statements.

How to streamline the select statement?

Current code:

let mut stmt = conn.prepare("SELECT pid, cat, plant, variety FROM plants")?;

println!("Columns  = {:?}", stmt.column_names());
println!("column 0 = {:?}", stmt.column_names()[0]);

// ************************MAP the rows using Plant struct
let plant_iter = stmt.query_map([], |row| {
    Ok(Plant {
        pid: row.get(0)?,
        cat: row.get(1)?,
        plant: row.get(2)?,
        variety: row.get(3)?,
    })
})?;

println!(); // ********************ITERATE over the mapped rows using struct
for plant in plant_iter {
    print!(
        "{}{} ",
        plant.as_ref().unwrap().pid,
        " ".repeat(4 - plant.as_ref().unwrap().pid.to_string().len())
    );
    print!(
        "{}{} ",
        plant.as_ref().unwrap().cat,
        " ".repeat(8 - plant.as_ref().unwrap().cat.to_string().len())
    );
    print!(
        "{}{} ",
        plant.as_ref().unwrap().plant,
        " ".repeat(10 - plant.as_ref().unwrap().plant.to_string().len())
    );
    print!(
        "{}{} ",
        plant.as_ref().unwrap().variety,
        " ".repeat(20 - plant.as_ref().unwrap().variety.to_string().len())
    );
}

Produces this:

Columns  = ["pid", "cat", "plant", "variety"]
column 0 = "pid"

1    veggie   tomato     Brandywine           
2    veggie   bok choy   prize                
3    veggie   cabbage    brunswick            

Is there a way to get the sqlite format ".mode column" with headers and data all at once with appealing column spacing?

Using the above data can the column headers and rows be combined using rusqlite?

Tried Rusqlite and expected to find a way to emulate sqlite's table view with select statement in rust using rusqlite. Still searching...

0

There are 0 answers