Skip to main content

DmClient

Struct DmClient 

Source
pub struct DmClient { /* private fields */ }
Expand description

达梦客户端:连接 / 查询 / 参数绑定 / LOB / 事务 / 存储过程 / 惰性查询。

Implementations§

Source§

impl DmClient

Source

pub fn new(host: &str, port: u16, user: &str, password: &str) -> Self

Examples found in repository?
examples/basic.rs (line 14)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn from_dsn(dsn: &str) -> Result<Self>

从 DSN 连接串创建客户端(不连接):dm://user:password@host:port/?encoding=utf8&timeout=15。 支持参数:encoding(字符集)、timeout(秒)、auto_reconnect(true/false)、 send_delay_ms(帧间隔毫秒)、app_name、os_name。

Source

pub fn connect_from_dsn(dsn: &str) -> Result<Self>

从 DSN 连接串创建并连接:dm://SYSDBA:password@127.0.0.1:5236/?encoding=auto。

Source

pub fn with_config(cfg: ClientConfig) -> Self

Source

pub fn config(&self) -> &ClientConfig

Source

pub fn is_connected(&self) -> bool

Source

pub fn auto_commit(&self) -> bool

Source

pub fn session_key(&self) -> Option<&[u8]>

Examples found in repository?
examples/basic.rs (line 16)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn server_encoding_name(&self) -> &'static str

当前使用的服务器字符集名(握手自动检测或手动指定,如 “GB18030”/“UTF-8”/“EUC-KR”)。

Source

pub fn set_lob_chunk_size(&mut self, size: usize)

Source

pub fn connect(&mut self) -> Result<()>

Examples found in repository?
examples/basic.rs (line 15)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn execute(&mut self, sql: &str, params: &[Param]) -> Result<ExecuteResult>

执行 SQL。params 为参数化查询的绑定参数。

Examples found in repository?
examples/basic.rs (line 19)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn execute_lazy( &mut self, sql: &str, params: &[Param], ) -> Result<(Vec<Column>, LazyState)>

惰性查询:只拉第一帧(fetchSize 行),返回 (cols, state)。 调用方用 fetch_more 按需拉取;用完必须 close_lazy。

Source

pub fn fetch_more( &mut self, stmt: i32, start_pos: i64, ncols: usize, ) -> Result<Vec<Row>>

惰性拉取下一批(cmd=7),循环直到取完全部行。返回追加的行(raw)。之后 state.more 为 false。

请求参数区:帧 20-27=startPos(int64),28-35=INT64_MAX(maxRows),36-39=id,40-43=bufPrefetch。 响应参数区:帧 20-27=总行数 int64(Go zq.go Dm_build_1068=20 / updateCount), 帧 28-31=本批行数 int32(Dm_build_1069=28)。 循环保护:空批即断 + 最大迭代上限(防服务器不返回总行数时误判死循环)。

Source

pub fn close_lazy(&mut self, state: &mut LazyState) -> Result<()>

释放惰性查询的 stmt(cmd=44 + cmd=4)。

Source

pub fn executemany( &mut self, sql: &str, params_list: &[Vec<Param>], ) -> Result<u64>

批量执行(协议级 batch,一组 cmd=5+13+4 插多行)。返回总影响行数。

Source

pub fn begin(&mut self) -> Result<()>

开始事务:设置隔离级别(cmd=52)+ 关闭自动提交(Go 实测顺序)

Examples found in repository?
examples/basic.rs (line 53)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn commit(&mut self) -> Result<()>

提交事务(cmd=8)

Source

pub fn rollback(&mut self) -> Result<()>

回滚事务(cmd=9)

Examples found in repository?
examples/basic.rs (line 55)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source

pub fn set_iso_level(&mut self, level: i32) -> Result<()>

设置事务隔离级别(cmd=52):1=读已提交 2=可重复读 3=串行化

Source

pub fn close(&mut self)

Examples found in repository?
examples/basic.rs (line 59)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let host = std::env::var("DM_HOST").unwrap_or_else(|_| "127.0.0.1".into());
10    let port: u16 = std::env::var("DM_PORT").unwrap_or_else(|_| "5236".into()).parse()?;
11    let user = std::env::var("DM_USER").unwrap_or_else(|_| "SYSDBA".into());
12    let pwd = std::env::var("DM_PWD").unwrap_or_else(|_| "password".into());
13
14    let mut c = DmClient::new(&host, port, &user, &pwd);
15    c.connect()?;
16    println!("✅ 连接成功,会话密钥前缀: {:02x?}...", &c.session_key().unwrap()[..4]);
17
18    // 1. 简单查询(非参数化)
19    let r = c.execute("select 1", &[])?;
20    if let ExecuteResult::Query { columns, rows } = r {
21        println!("select 1 => cols={:?} rows={:?}", columns.iter().map(|c| &c.name).collect::<Vec<_>>(), rows);
22    }
23
24    // 2. 参数化查询(先建表)
25    c.execute(
26        "CREATE TABLE IF NOT EXISTS rust_demo (id INT, name VARCHAR(100), d DATE, f DOUBLE)",
27        &[],
28    )?;
29    let r = c.execute(
30        "INSERT INTO rust_demo VALUES (?, ?, ?, ?)",
31        &[
32            Param::Int(1),
33            Param::Str("测试".into()),
34            Param::Date(dm_pure::DmDate::new(2026, 8, 12)),
35            Param::Float(std::f64::consts::PI),
36        ],
37    )?;
38    println!("INSERT affected: {:?}", r.affected());
39
40    let r = c.execute("SELECT id, name, d, f FROM rust_demo WHERE id >= ?", &[Param::Int(1)])?;
41    if let ExecuteResult::Query { columns, rows } = r {
42        println!("查询 {} 列, {} 行:", columns.len(), rows.len());
43        for row in &rows {
44            println!("  {:?}", row);
45        }
46    }
47
48    // 3. 存储过程 OUT 参数
49    // c.execute("CALL sp_test(?, ?, ?, ?)", &[Param::Int(5), Param::Str("hello".into()),
50    //     Param::out(Some(OutType::Int)), Param::out(Some(OutType::Str))])?;
51
52    // 4. 事务
53    c.begin()?;
54    c.execute("UPDATE rust_demo SET name = ? WHERE id = ?", &[Param::Str("改".into()), Param::Int(1)])?;
55    c.rollback()?; // 回滚
56    println!("事务回滚完成");
57
58    c.execute("DROP TABLE rust_demo", &[])?;
59    c.close();
60    println!("✅ 示例结束");
61    Ok(())
62}
Source§

impl DmClient

DmClient 的事务入口。

Source

pub fn transaction(&mut self) -> Result<Transaction<'_>>

开始事务并返回 Transaction 句柄(Drop 自动回滚)。

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V