Rust: PostgreSQL のデータを作成 (Create)


Cargo.toml
[package]
name = "postgres_create"
version = "0.1.0"
edition = "2018"

[dependencies]
postgres = "*"
src/main.rs
// --------------------------------------------------------------------
/*
    postgres_create/src/main.rs

                    Jul/24/2020
*/
// --------------------------------------------------------------------
use postgres::{Client, NoTls, Error};

// --------------------------------------------------------------------
fn insert_proc(client:&mut Client,key:&'static str,
    name:&'static str,population: i32,date_mod:&'static str)
     -> Result<(), Error> {

    let sql_str = "INSERT INTO cities (id,name, population,date_mod) VALUES ('".to_string()
         + &key.to_string() + "','" + name + "',"
         + &population.to_string() + ",'" + date_mod + "')";

    eprintln!("{}",sql_str);

    client.batch_execute(&sql_str)?;

    Ok(())
}

// --------------------------------------------------------------------
fn main() -> Result<(), Error> {
    eprintln!("*** start ***");
    let mut client = Client::connect("postgresql://scott:tiger123@localhost/city", NoTls)?;


    client.batch_execute("drop table cities
    ")?;

    client.batch_execute("
        CREATE TABLE IF NOT EXISTS cities  (
            id  varchar(10) primary key,
            name    VARCHAR(20),
            population  int,
            date_mod    varchar(20)
            )
    ")?;

    let _ = insert_proc(&mut client,"t3461","広島",38415,"1956-5-18");
    let _ = insert_proc(&mut client,"t3462","福山",42978,"1956-9-21");
    let _ = insert_proc(&mut client,"t3463","東広島",17246,"1956-3-7");
    let _ = insert_proc(&mut client,"t3464","呉",37416,"1956-10-11");
    let _ = insert_proc(&mut client,"t3465","尾道",45971,"1956-2-25");
    let _ = insert_proc(&mut client,"t3466","竹原",19243,"1956-7-9");
    let _ = insert_proc(&mut client,"t3467","三次",97456,"1956-11-12");
    let _ = insert_proc(&mut client,"t3468","大竹",25931,"1956-5-6");
    let _ = insert_proc(&mut client,"t3469","府中",89173,"1956-12-19");

    eprintln!("*** end ***");
    Ok(())

}

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

実行コマンド

cargo run