5 个稳定版本

23.0.2 2023 年 6 月 6 日
23.0.1 2023 年 2 月 5 日
23.0.0 2022 年 11 月 19 日
22.2.1 2022 年 9 月 30 日

#2456数据库接口

MIT/Apache

340KB
7K SLoC

WASI 的简单 mysql 驱动程序

此 crate 提供

  • 纯 Rust 的 MySql 数据库驱动程序;
  • 连接池;
  • 编译为 WebAssembly 并在 WasmEdge 运行时 中运行,作为 Linux 容器的轻量级替代方案;
  • WASI 驱动程序目前不支持 SSL/TLS 数据库连接

有关更多详细信息和使用示例,请参阅上游 rust-mysql-simple 源代码和 此示例

安装

将所需的 crate 版本放入您的 dependencies 部分的 Cargo.toml

[dependencies]
mysql_wasi = "23.0.1"

示例

use mysql::*;
use mysql::prelude::*;

#[derive(Debug, PartialEq, Eq)]
struct Payment {
    customer_id: i32,
    amount: i32,
    account_name: Option<String>,
}


fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let url = "mysql://root:password@localhost:3307/db_name";
    # Opts::try_from(url)?;
    # let url = get_opts();
    let pool = Pool::new(url)?;

    let mut conn = pool.get_conn()?;

    // Let's create a table for payments.
    conn.query_drop(
        r"CREATE TEMPORARY TABLE payment (
            customer_id int not null,
            amount int not null,
            account_name text
        )")?;

    let payments = vec![
        Payment { customer_id: 1, amount: 2, account_name: None },
        Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) },
        Payment { customer_id: 5, amount: 6, account_name: None },
        Payment { customer_id: 7, amount: 8, account_name: None },
        Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) },
    ];

    // Now let's insert payments to the database
    conn.exec_batch(
        r"INSERT INTO payment (customer_id, amount, account_name)
          VALUES (:customer_id, :amount, :account_name)",
        payments.iter().map(|p| params! {
            "customer_id" => p.customer_id,
            "amount" => p.amount,
            "account_name" => &p.account_name,
        })
    )?;

    // Let's select payments from database. Type inference should do the trick here.
    let selected_payments = conn
        .query_map(
            "SELECT customer_id, amount, account_name from payment",
            |(customer_id, amount, account_name)| {
                Payment { customer_id, amount, account_name }
            },
        )?;

    // Let's make sure, that `payments` equals to `selected_payments`.
    // Mysql gives no guaranties on order of returned rows
    // without `ORDER BY`, so assume we are lucky.
    assert_eq!(payments, selected_payments);
    println!("Yay!");

    Ok(())
}

许可证

在您的选择下,受以下任一许可证的约束:

贡献

除非您明确表示,否则根据 Apache-2.0 许可证定义的,您有意提交的工作的所有贡献均应按上述方式双许可,不附加任何额外条款或条件。

依赖关系

~11–28MB
~475K SLoC