Connecting to a Database
sqlx pools.
Connecting to a Database is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is sqlx?
sqlx is an async, pure-Rust SQL toolkit. It is not an ORM; you write real SQL but get compile-time checking and type-safe results.
- Supports Postgres, MySQL, SQLite
- Built on async runtimes like Tokio
Adding sqlx
Declare sqlx with the runtime and database features you need. This edits Cargo.toml and runs in your terminal.
[dependencies]
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
tokio = { version = "1", features = ["full"] }Connection strings
A connection string (DSN) tells sqlx how to reach the database.
- Postgres:
postgres://user:pass@host:5432/dbname - SQLite:
sqlite://app.db
Why a connection pool?
Opening a connection per query is slow. A pool keeps a set of reusable connections and hands them out as needed, then returns them.
- Bounds concurrency
- Amortizes connection cost
Creating a pool
Use PgPoolOptions to configure and connect a pool. This is typically done once at startup.
use sqlx::postgres::PgPoolOptions;
async fn connect() -> sqlx::Pool<sqlx::Postgres> {
PgPoolOptions::new()
.max_connections(5)
.connect("postgres://user:pass@localhost/app")
.await
.unwrap()
}Configuring the pool
Tune the pool with options like max connections and acquire timeout to match your workload.
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;
fn options() -> PgPoolOptions {
PgPoolOptions::new()
.max_connections(10)
.acquire_timeout(Duration::from_secs(3))
}A simple query through the pool
Pass the pool (or a reference to it) as the executor to run a query. The pool checks out a connection automatically.
use sqlx::Pool;
use sqlx::Postgres;
async fn ping(pool: &Pool<Postgres>) -> i32 {
let row: (i32,) = sqlx::query_as("SELECT 1")
.fetch_one(pool)
.await
.unwrap();
row.0
}Modeling a pool in plain Rust
A pool is conceptually a bounded collection of reusable resources. This runnable example sketches checkout and return.
struct Pool { available: u32, max: u32 }
impl Pool {
fn acquire(&mut self) -> bool {
if self.available > 0 { self.available -= 1; true } else { false }
}
fn release(&mut self) { self.available += 1; }
}
fn main() {
let mut p = Pool { available: 2, max: 2 };
println!("{}", p.acquire());
println!("{}", p.acquire());
println!("{}", p.acquire());
p.release();
println!("{}", p.acquire());
}Reading the DSN from env
Keep secrets out of source code. Read DATABASE_URL from the environment at startup.
use sqlx::postgres::PgPoolOptions;
async fn connect() -> sqlx::Pool<sqlx::Postgres> {
let url = std::env::var("DATABASE_URL").unwrap();
PgPoolOptions::new().connect(&url).await.unwrap()
}Cloning is cheap
A Pool is internally reference-counted. Cloning it shares the same underlying connections, so you can pass clones to tasks freely.
use sqlx::{Pool, Postgres};
async fn spawn_work(pool: Pool<Postgres>) {
let p2 = pool.clone();
tokio::spawn(async move {
let _ = sqlx::query("SELECT 1").execute(&p2).await;
});
}Closing the pool
On shutdown, call close().await to gracefully drain and close all connections.
use sqlx::{Pool, Postgres};
async fn shutdown(pool: Pool<Postgres>) {
pool.close().await;
}Quick Check
Test your understanding of connecting with sqlx.
Recap
You learned to connect with sqlx:
- sqlx is an async, type-safe SQL toolkit, not an ORM
- A DSN describes the database location
- Use
PgPoolOptionsto build a pool with limits and timeouts - Pools are cheap to clone and should be closed on shutdown
Next: compile-time checked queries.
Frequently asked questions
Is the “Connecting to a Database” lesson free?
Yes — the full text of “Connecting to a Database” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Connecting to a Database”?
sqlx pools. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Connecting to a Database” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Connecting to a Database
- Compile-Time Checked Queries
- CRUD Operations
- Migrations