3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust: MariaDB のデータを読む (Read)

Last updated at Posted at 2020-07-12

こちらのページと同様のことを行いました。
Rustで直接SQLを書いてMySQLからデータを抽出する方法

Ubuntu 20.4 で必要となるライブラリーのインストール

sudo apt install libmariadb-client-lgpl-dev-compat

フォルダー構造

$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── main.rs
│   └── utils.rs
└── target
    └── debug
Cargo.toml
[package]
name = "read"
version = "0.1.0"
edition = "2018"

#

[dependencies]
diesel = { version = "*", features = ["mysql"] }
src/main.rs
// --------------------------------------------------------------------
/*
	read/src/main.rs

					Jul/20/2020
*/
// --------------------------------------------------------------------

use crate::utils::establish_connection;
// use chrono::NaiveDateTime;
// use chrono::DateTime;

use diesel::deserialize::QueryableByName;
use diesel::mysql::MysqlConnection;
use diesel::prelude::*;
use diesel::sql_query;

mod utils;

type DB = diesel::mysql::Mysql;

#[derive(Debug)]
pub struct Cities {
    id: String,
    name: String,
    population: i32,
	date_mod: String,
//	date_mod: DateTime,
}

// --------------------------------------------------------------------
impl QueryableByName<DB> for Cities {
    fn build<R: diesel::row::NamedRow<diesel::mysql::Mysql>>(
        row: &R,
    ) -> diesel::deserialize::Result<Self> {
        Ok(Cities {
            id: row.get("id")?,
            name: row.get("name")?,
            population: row.get("population")?,
	date_mod: row.get("date_mod")?,
        })
    }
}

// --------------------------------------------------------------------
fn simple_sql() {
    let connection: MysqlConnection = establish_connection();
    let cities: Vec<Cities> = sql_query(
        "SELECT id, name, population, date_mod FROM cities",
    )
    .load(&connection)
    .unwrap();

//    println!("{:?}", cities);

	for uu in cities.iter(){
//		println!("{:?}",uu);
		println!("{}\t{}\t{}\t{}",uu.id,uu.name,uu.population,uu.date_mod);
		}
}

// --------------------------------------------------------------------
fn main (){
	eprintln! ("*** 開始 ***");
	simple_sql();
	eprintln! ("*** 終了 ***");
}

// --------------------------------------------------------------------
src/utils.rs
// --------------------------------------------------------------------
/*
	src/utils.rs

					Jul/12/2020
*/
// --------------------------------------------------------------------
use diesel::mysql::MysqlConnection;
use diesel::prelude::*;

pub fn establish_connection() -> MysqlConnection {
    let database_url = "mysql://scott:tigermask@localhost:3306/city";
    MysqlConnection::establish(&database_url)
        .expect(&format!("Error connecting to {}", database_url))
}

// --------------------------------------------------------------------

コンパイル

carogo build

実行

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/read`
*** 開始 ***
t3321	岡山	43781	2000-3-15
t3322	倉敷	79124	2000-8-9
t3323	津山	31586	2000-6-21
t3324	玉野	52647	2000-10-12
t3325	笠岡	82631	2000-9-25
*** 終了 ***
3
3
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?