当先锋百科网

首页 1 2 3 4 5 6 7
文件名称版本号作者qq组件版本
rust增删改查v1.0.1学生宫布8416837rust 1.44.1
mysql_async = "0.22.2"等

建表、插入并查询

  1. 步骤
  1. 依赖
[dependencies]
rand = "0.3.17"
mysql = "*"
  1. code
extern crate rand;
use mysql::*;
use mysql::prelude::Queryable;
use rand::Rng;

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

fn gen_db_conn(conn: PooledConn){
}

fn main() {
    let url = "mysql://root:root@localhost:3306/bootdo-cc";

    let pool: Pool = match Pool::new(url) {
        Ok(pool) => pool,
        Err(e) => return ()
    };

    let mut conn = match pool.get_conn() {
        Ok(conn) => conn,
        Err(e) => return ()
    };

    let mut rng = rand::thread_rng();
    // Let's create a table for payments.
    let mut ret = conn.query_drop(
        r"CREATE TEMPORARY TABLE payment (
        customer_id int not null,
        amount int not null,
        account_name text
    )"); // 创建临时表,释放连接时删除或自定义删除时机
//    )")?;
    println!("创建临时表:{:#?}", ret);

    let payments = vec![
        Payment { customer_id: rng.gen::<u32>(), amount: 2, account_name: None },
        Payment { customer_id: rng.gen::<u32>(), amount: 4, account_name: Some("鸿钧老祖".into()) },
        Payment { customer_id: rng.gen::<u32>(), amount: 6, account_name: Some(String::from("赵公明")) },
        Payment { customer_id: 9527, amount: 8, account_name: None },
        Payment { customer_id: rng.gen::<u32>(), amount: 10, account_name: Some("镇元子".into()) },
    ];

// Now let's insert payments to the database
    ret = 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,
    })
    );
//    )?;
    println!("插入数据:{:#?}", ret);

    // 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); // 报错:can't compare `std::vec::Vec<Payment>` with `std::result::Result<std::vec::Vec<Payment>, mysql::error::Error>`
    println!("查询:{:#?}", selected_payments);
    println!("~~~完成~~~");
}
  1. output
创建临时表:Ok(
    (),
)
插入数据:Ok(
    (),
)
查询:Ok(
    [
        Payment {
            customer_id: 2147483647,
            amount: 2,
            account_name: None,
        },
        Payment {
            customer_id: 1640159754,
            amount: 4,
            account_name: Some(
                "鸿钧老祖",
            ),
        },
        Payment {
            customer_id: 1430621896,
            amount: 6,
            account_name: Some(
                "赵公明",
            ),
        },
        Payment {
            customer_id: 9527,
            amount: 8,
            account_name: None,
        },
        Payment {
            customer_id: 2147483647,
            amount: 10,
            account_name: Some(
                "镇元子",
            ),
        },
    ],
)
~~~完成~~~

查询已有表

  1. code
use mysql::*;
use mysql::prelude::Queryable;

#[derive(Debug, PartialEq, Eq)]
struct User {
    username: Option<String>,
    password: Option<String>,
    name: Option<String>,
}

fn main() {
    let url = "mysql://root:root@localhost:3306/rustcc_test";
    let pool: Pool = match Pool::new(url) {
        Ok(pool) => pool,
        Err(e) => return ()
    };

    let mut conn = match pool.get_conn() {
        Ok(conn) => conn,
        Err(e) => return ()
    };

//    println!("{:#?}", conn)
    let selected_users = conn
        .query_map(
            "SELECT USERNAME,PASSWORD, NAME FROM SYS_USER ORDER BY GMT_MODIFIED ASC  LIMIT 1",
            |(username, password, name)| {
                User { username, password, name }
            },
        );
    println!("查询结果:{:#?}", selected_users);
}
  1. output
查询结果:Ok(
    [
        User {
            username: Some(
                "ytg",
            ),
            password: Some(
                "4eb1bda86bc02bf6478ca71e42135d2f",
            ),
            name: Some(
                "YuanTiangang",
            ),
        },
    ],
)