الاتصال بقاعدة بيانات
مجمّعات sqlx
الاتصال بقاعدة بيانات درس مجاني في Learn Rust Coding على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Learn Rust Coding، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
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.
الأسئلة الشائعة
هل درس «الاتصال بقاعدة بيانات» مجاني؟
نعم — نص درس «الاتصال بقاعدة بيانات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Learn Rust Coding، انتقل إلى CoddyKit PRO. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.
ماذا ستتعلم في «الاتصال بقاعدة بيانات»؟
مجمّعات sqlx تتمرن على Learn Rust Coding مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Learn Rust Coding؟
لا تُشترط خبرة سابقة. Learn Rust Coding على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «الاتصال بقاعدة بيانات»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Learn Rust Coding هذا؟
نعم. كل درس في Learn Rust Coding يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- الاتصال بقاعدة بيانات
- استعلامات متحقَّق منها وقت الترجمة
- عمليات CRUD
- الترحيلات