Skip to content

Instantly share code, notes, and snippets.

@arossouw
Created April 23, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arossouw/16288473cbcccc4d4522 to your computer and use it in GitHub Desktop.
Save arossouw/16288473cbcccc4d4522 to your computer and use it in GitHub Desktop.
Newbie simple select query - mysql-simple
extern crate mysql;
extern crate time;
use mysql::conn::{MyOpts};
use mysql::value::Value;
use mysql::conn::pool::{MyPool};
use mysql::value::{from_value};
use std::default::{Default};
use std::vec::Vec;
struct Payment {
customer_id : i32,
amount : f32
}
fn main()
{
let opts = MyOpts{
user: Some("mysqluser".to_string()),
pass: Some("mysqluser".to_string()),
db_name: Some("dbsales".to_string()),
tcp_addr: Some("10.0.0.82".to_string()),
..Default::default()
};
let pool = MyPool::new(opts).unwrap();
pool.prepare("SELECT customer_id,amount from payment LIMIT 5").map(|mut stmt| {
let mut result = stmt.execute(&[]).unwrap();
for row in result {
let payment = Payment {
customer_id : row[0],
amount : row[1]
};
//assert_eq!(row.unwrap(), vec![Value::Int(42)]);
println!("Found payment {} {}" , payment.customer_id, payment.amount);
}
});
}
@blackbeam
Copy link

extern crate mysql;

use std::default::Default;

use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;

#[derive(Debug, PartialEq, Eq)]
struct Payment {
    customer_id: i32,
    amount: i32,
}

fn main() {
    let opts = MyOpts {
        user: Some("root".into()),
        pass: Some("password".into()),
        tcp_port: 3307,
        ..Default::default()
    };
    let pool = MyPool::new(opts).unwrap();

    // Let's create payment table.
    // It is temporary so we do not need `tmp` database to exist.
    // We will use into_iter() because we does not need to map Stmt to anything else.
    // Also we assume that no error happened in `prepare`.
    for mut stmt in pool.prepare("CREATE TEMPORARY TABLE tmp.payment (customer_id int, amount int)").into_iter() {
        // Unwap just to make sure no error happened
        stmt.execute(&[]).unwrap();
    }

    let payments = vec![
        Payment { customer_id: 1, amount: 2 },
        Payment { customer_id: 3, amount: 4 },
        Payment { customer_id: 5, amount: 6 },
        Payment { customer_id: 7, amount: 8 },
        Payment { customer_id: 9, amount: 10 },
    ];

    // Let's insert payments to the database
    // We will use into_iter() because we does not need to map Stmt to anything else.
    // Also we assume that no error happened in `prepare`.
    for mut stmt in pool.prepare("INSERT INTO tmp.payment (customer_id, amount) VALUES (?, ?)").into_iter() {
        for p in payments.iter() {
            // Unwrap each result just to make sure no errors happended
            stmt.execute(&[&p.customer_id, &p.amount]).unwrap();
        }
    }


    // Let's select payments from the database
    let selected_payments: Vec<Payment> = pool.prepare("SELECT customer_id, amount from tmp.payment")
    .and_then(|mut stmt| { // In this closure we will map Stmt to Vec<Payment>
        // Here we must use nested `and_than` because stmt must be in scope while working with QueryResult
        stmt.execute(&[]).and_then(|result| { // In this closure we will map QueryResult to Vec<Payment>
            // QueryResult is iterator over MyResult<row,err>
            // so first call to map will map each MyResult to contained row
            // and second call to map will map each row to Payment
            Ok(result.map(|x| x.unwrap()).map(|row| {
                Payment {
                    customer_id: from_value(&row[0]),
                    amount: from_value(&row[1]),
                }
            }).collect()) // Collect payments and wrap it in Ok() so now QueryResult is mapped to Vec<Payment>
        }) // bubble up Vec<Payment> to upper level `and_than`
    }).unwrap(); // Unwrap Vec<Payment>

    // Now make shure that payments equals selected_payments
    // mysql gives no guaranties on order of returned rows without ORDER BY so assume we are lukky
    assert_eq!(payments, selected_payments);
    println!("Yay!");
}

@arossouw
Copy link
Author

Thanks , much appreciated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment