📜  rust sqlx (1)

📅  最后修改于: 2023-12-03 15:04:57.721000             🧑  作者: Mango

Rust SQLx

Rust SQLx is a high-performance SQL toolkit for Rust programming language which provides a simple and intuitive interface to interact with databases. It allows Rust programmers to write type-safe SQL queries with compile-time guarantees and supports multiple databases such as PostgreSQL, MySQL, SQLite, and Microsoft SQL Server.

Features
  • Compile-time query validation and type checking
  • Support for multiple databases
  • Asynchronous database I/O using async/await syntax
  • Automatic connection pooling and reconnection handling
  • Support for prepared statements and transactions
  • Raw SQL string execution
  • High-performance zero-copy data deserialization
  • Thread safety with concurrent query execution
Getting started

To use Rust SQLx, add the following dependency to your Cargo.toml file:

[dependencies]
sqlx = "0.5"
sqlx-core = "0.4"

Then, you can establish a connection to your desired database by creating a Pool:

use sqlx::postgres::PgPool;
use sqlx::Pool;

let pool = PgPool::new("postgres://user:password@localhost/database_name").await?;

Once you have a Pool, you can execute SQL queries on it:

use sqlx::postgres::PgQueryAs;
use sqlx::Row;

let rows = sqlx::query_as::<_, (i32, String)>("SELECT id, name FROM users")
    .fetch_all(&pool)
    .await?;

for row in rows {
    let id: i32 = row.get(0);
    let name: String = row.get(1);

    println!("User {} is named {}", id, name);
}
Conclusion

If you are looking for a fast, safe, and easy-to-use SQL toolkit for Rust programming language, Rust SQLx is a perfect fit for you. With Rust's strong type system and SQLx's compile-time validation, you can write SQL queries with confidence and reduce runtime errors. Start using Rust SQLx today and unleash the full power of Rust and databases.