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.Get the database URL:
turso db show --url <database-name> 
Get the database authentication token:
turso db tokens create <database-name> 
Assign credentials to the environment variables inside .env.
TURSO_DATABASE_URL= TURSO_AUTH_TOKEN= 
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 = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set");  let db = Builder::new_remote_replica("local.db", url, token)  .build()  .await?; let conn = db.connect()?; 
use libsql::Builder;  let db = Builder::new_local("local.db").build().await?; let conn = db.connect()?; 
use libsql::Builder;  let url = std::env::var("TURSO_DATABASE_URL").expect("TURSO_DATABASE_URL must be set"); let token = std::env::var("TURSO_AUTH_TOKEN").expect("TURSO_AUTH_TOKEN must be set");  let db = Builder::new_remote(url, token)  .build()  .await?; let conn = db.connect()?; 
4

Execute

You can execute a SQL query against your existing database by calling execute():
conn.execute("SELECT * FROM users", ()).await?; 
If you need to use placeholders for values, you can do that:
conn.execute("SELECT * FROM users WHERE id = ?1", libsql::params![1]).await?; 
To retrieve results from a query, you can use the query() method:
let mut rows = conn.query("SELECT * FROM users", ()).await?;  while let Some(row) = rows.next().await? {  let id: i64 = row.get(0)?;  let name: String = row.get(1)?;  println!("User: {} - {}", id, name); } 
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:
db.sync().await.unwrap(); 
You can also set up automatic periodic syncing when creating the database:
use std::time::Duration;  let db = Builder::new_remote_replica("local.db", url, token)  .sync_interval(Duration::from_secs(60))  .build()  .await?; 
This will automatically sync the database every 60 seconds.