Import export cvs file to mariadb database mysql rust

⚓ Rust    📅 2025-09-01    👤 surdeus    👁️ 3      

surdeus

[dependencies]
csv = "1.1"
mysql = "20.1"

use std::error::Error;
use std::fs::File;
use csv::ReaderBuilder;
use mysql::{Pool, prelude::*};

fn import_csv_to_mariadb(file_path: &str, db_url: &str) -> Result<(), Box> {
//
let pool = Pool::new(db_url)?;
let mut conn = pool.get_conn()?;

// 
let file = File::open(file_path)?;
let mut rdr = ReaderBuilder::new().has_headers(true).from_reader(file);

// 
for result in rdr.records() {
    let record = result?;
    let col1: String = record.get(0).unwrap().to_string();
    let col2: i32 = record.get(1).unwrap().parse()?;

    conn.exec_drop(
        "INSERT INTO your_table_name (column1, column2) VALUES (:col1, :col2)",
        params! {
            "col1" => col1,
            "col2" => col2,
        },
    )?;
}

Ok(())

}

use std::error::Error;
use std::fs::File;
use csv::Writer;
use mysql::{Pool, prelude::*};

fn export_mariadb_to_csv(file_path: &str, db_url: &str) -> Result<(), Box> {
//
let pool = Pool::new(db_url)?;
let mut conn = pool.get_conn()?;

//  
let results: Vec<(String, i32)> = conn.query("SELECT column1, column2 FROM your_table_name")?;

//  
let mut wtr = Writer::from_writer(File::create(file_path)?);
for (col1, col2) in results {
    wtr.write_record(&[col1, col2.to_string()])?;
}
wtr.flush()?;

Ok(())

}

use std::error::Error;
use std::fs::File;
use csv::Writer;
use mysql::{Pool, prelude::*};

fn export_mariadb_to_csv(file_path: &str, db_url: &str) -> Result<(), Box> {
//
let pool = Pool::new(db_url)?;
let mut conn = pool.get_conn()?;

//  
let results: Vec<(String, i32)> = conn.query("SELECT column1, column2 FROM your_table_name")?;

//  
let mut wtr = Writer::from_writer(File::create(file_path)?);
for (col1, col2) in results {
    wtr.write_record(&[col1, col2.to_string()])?;
}
wtr.flush()?;

Ok(())

}

1 post - 1 participant

Read full topic

🏷️ Rust_feed