Skip to content

Instantly share code, notes, and snippets.

@umuro
Created October 27, 2023 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umuro/65db5bff55269d7313f07d9059d6cc85 to your computer and use it in GitHub Desktop.
Save umuro/65db5bff55269d7313f07d9059d6cc85 to your computer and use it in GitHub Desktop.
Using SQLite with Rust

Here's a step-by-step process of how you can work with SQLite in a Rust project:

  1. Choose a Library:

    • rusqlite: This is a popular choice for working with SQLite in Rust. It provides a safe and comfortable wrapper around the SQLite C API.
    • diesel: While not SQLite-specific, Diesel is a powerful ORM (Object-Relational Mapping) and query builder for Rust that supports SQLite, among other databases.
  2. Install the Library:

    • Add the library to your Cargo.toml file.

    toml code

    [dependencies] rusqlite = "0.24"

  3. Create and Connect to a Database:

    • With the library installed, you can now create a database and establish a connection.

    rust code

    extern crate rusqlite; use rusqlite::{Connection, Result}; fn main() -> Result<()> { let conn = Connection::open("database.db")?; Ok(()) }

  4. Create Tables:

    • Define and create tables in your SQLite database.

    rust code

    conn.execute( "CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER )", [], )?;

  5. Insert Data:

    • Insert data into your database tables.

    rust code

    conn.execute( "INSERT INTO users (name, age) VALUES (?1, ?2)", &[&"Alice", &30], )?;

  6. Query Data:

    • Use the library's query APIs to retrieve data from your database.

    rust code

    let mut stmt = conn.prepare("SELECT name, age FROM users")?; let user_iter = stmt.query_map([], |row| { Ok(( row.get::<_, String>(0)?, row.get::<_, i32>(1)? )) })?; for user in user_iter { println!("{:?}", user?); }

  7. Update and Delete Data:

    • Use SQL commands to update or delete data in your database.

    rust code

    conn.execute( "UPDATE users SET age = ?1 WHERE name = ?2", &[&35, &"Alice"], )?; conn.execute( "DELETE FROM users WHERE name = ?1", &[&"Bob"], )?;

  8. Handle Errors:

    • Handle any errors that might occur when working with the database.

    rust code

    fn main() -> Result<()> { let conn = Connection::open("database.db").expect("Unable to open database"); // ... Ok(()) }

  9. Close the Connection:

    • It's good practice to close the connection to the database when done.
    • With rusqlite, the connection will be closed automatically when the Connection object goes out of scope.
  10. Optimize Performance (Optional):

*   Consider using prepared statements for queries you'll execute multiple times.
*   Use transactions to batch multiple operations together.

By following these steps, you should have a solid foundation for working with SQLite databases in your Rust applications.

Umur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment