Skip to main content

cursor_pool/
cursor_pool.rs

1//! DB-API 风格惰性游标示例:fetchone / fetchmany / fetchall + 连接池。
2
3use dm_pure::{ClientConfig, ConnectionPool, Cursor, Param};
4
5fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let cfg = ClientConfig {
7        host: std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into()),
8        port: std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?,
9        user: std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into()),
10        password: std::env::var("DM_PWD").unwrap_or_else(|_| "password".into()),
11        ..Default::default()
12    };
13
14    // 连接池(最小 1 / 最大 5)
15    let pool = ConnectionPool::new(cfg, 1, 5)?;
16    {
17        let mut conn = pool.acquire()?;
18        {
19            let mut cur = conn.cursor();
20            cur.execute("select 1", &[])?;
21            println!("description: {:?}", cur.description());
22            while let Some(row) = cur.fetchone()? {
23                println!("row: {:?}", row);
24            }
25        }
26        // 惰性游标:大结果集自动分批拉取
27        {
28            let mut cur: Cursor = conn.cursor();
29            cur.execute("SELECT id FROM proto_test WHERE id >= ?", &[Param::Int(0)])?;
30            let rows = cur.fetchall()?;
31            println!("fetchall {} 行", rows.len());
32        }
33    } // Drop 自动归还连接
34
35    // executemany 批量插入
36    {
37        let mut conn = pool.acquire()?;
38        let batch: Vec<Vec<Param>> = (0..10)
39            .map(|i| vec![Param::Int(i), Param::Str(format!("name-{i}"))])
40            .collect();
41        let mut cur = conn.cursor();
42        let n = cur.executemany("INSERT INTO batch_demo VALUES (?, ?)", &batch)?;
43        println!("executemany 影响行数: {n}");
44    }
45
46    pool.close();
47    println!("✅ 游标/连接池示例结束");
48    Ok(())
49}