loudsilence
2 min readFeb 27, 2024

Support me by buying an item from my wishlist, visiting my reviews site or buy me a coffee!

Getting Started with SQLx and PostgreSQL in Rust

Rust is a systems programming language that promises to provide memory safety, concurrency, and performance with a focus on zero-cost abstractions, minimal runtime, and improved productivity. One of the areas where Rust shines is in web development, and a crucial part of web development is interacting with databases. This is where SQLx and PostgreSQL come in.

Introduction to SQLx

SQLx is an async, pure Rust SQL crate featuring compile-time checked queries without a DSL. It enables you to interact with PostgreSQL in a safe and efficient manner, leveraging Rust’s powerful type system.

Setting Up Your Environment

Before we start, make sure you have Rust installed. If not, you can install it from the official website. You’ll also need to have PostgreSQL installed and running.

Creating a New Project

Create a new Rust project by running the following command in your terminal:

cargo new sqlx_demo
cd sqlx_demo

Adding Dependencies

Open your Cargo.toml file and add the following lines under [dependencies]:

sqlx = { version = "0.5", features = ["postgres", "runtime-tokio-native-tls"] }
tokio = { version = "1", features = ["full"] }

Writing Code

In your main.rs file, write the following code:

use sqlx::postgres::PgPoolOptions;
use sqlx::Row;

#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://username:password@localhost/database_name")
.await?;

let row: (i64,) = sqlx::query_as("SELECT $1")
.bind(150_i64)
.fetch_one(&pool)
.await?;

println!("Got: {:?}", row.0);

Ok(())
}

This code connects to your PostgreSQL database and executes a simple SQL query.

Running Your Code

You can now run your code using the following command:

cargo run

Conclusion

This is a basic introduction to using SQLx with PostgreSQL in Rust. SQLx provides a powerful, idiomatic, and safe way to interact with databases in Rust. With SQLx and Rust, you can build robust, high-performance web applications.

Remember, this is just the beginning. SQLx offers much more, including transaction support, connection pooling, and compile-time query validation. Happy coding!🦀

Support me by buying an item from my wishlist, visiting my reviews site or buy me a coffee!

Learn More

No responses yet