Skip to main content
In this Rust quickstart we will learn how to:
  • Retrieve database credentials
  • Install the Rust libSQL crate
  • Connect to a local or remote Turso database
  • Execute a query using SQL
  • Sync changes to local database (optional)
1

Retrieve database credentials

You will need an existing database to continue. If you don’t have one, create one.
turso db show <database-name> --url
turso db tokens create <database-name>
You will want to store these as environment variables.
2

Install

First begin by installing the libsql crate:
cargo add libsql
3

Connect

You must first create a Database object and then open a Connection to it:
use libsql::Builder;

let url = env::var("LIBSQL_URL").expect("LIBSQL_URL must be set");
let token = env::var("LIBSQL_AUTH_TOKEN").unwrap_or_default();

let mut db = Builder::new_remote_replica("local.db", &url, &token).build().await.unwrap();
let conn = db.connect().unwrap();
use libsql::Builder;

let db = Builder::new_local("local.db").build().await?;
let conn = db.connect().unwrap();
use libsql::Builder;

let url = env::var("LIBSQL_URL").expect("LIBSQL_URL must be set");
let token = env::var("LIBSQL_AUTH_TOKEN").unwrap_or_default();

let db = Builder::new_remote(&url, &token).build().await?;
let conn = db.connect().unwrap();
4

Execute

You can execute a SQL query against your existing database by calling execute():
conn.execute("SELECT * FROM users", ()).await.unwrap();
If you need to use placeholders for values, you can do that:
conn.execute("SELECT * FROM users WHERE id = ?1", libsql::params![1]).await?;
5

Sync (Embedded Replicas only)

When using embedded replicas you should call sync() on the database type to sync your local database with the primary database, unless you are using periodic_sync (though there is no issue with calling sync with periodic_sync enabled):
db.sync().await.unwrap();