0
0

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 1 year has passed since last update.

Rust Diesel(1.4.8) でMySqlクエリを直接叩く

Posted at

なんかシンプルに使いたいときのメモ。
diesel 2.0.0以降だとまた様相が違いそう。気が向いたら書く。


use diesel::deserialize::QueryableByName;
use diesel::{MysqlConnection, RunQueryDsl, sql_query};

// テーブルから読み込むための構造体
#[derive(Debug)]
pub struct HogeRecord {
    pub id: u64,
    pub hoge_num: u64,
}

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

impl HogeRecord {
    // シンプルな読み込み
    pub fn read () -> Vec<HogeRecord>{
        let conn = MysqlConnection::establish("DBのURL").unwrap();
        
        // 適当なクエリ
        let query = format!("SELECT id,hoge_num FROM hoges;");
        
        // selectならload関数使う
        let records: Vec<HogeRecord> = sql_query(query).load(conn).unwrap();

        records
    }
    
    // シンプルな書き込み
    pub fn write () {
        let conn = MysqlConnection::establish("DBのURL").unwrap();
        
        // 適当なクエリ
        let query = format!("UPDATE hoges SET hoge_num = 1");
        
        // updateとかinsertならexecute関数使う
        sql_query(query).execute(conn).unwrap();

    }
}

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?