본문 바로가기
Rust

[Rust] MySQL 연결 및 Data 적재 (62일차)

by 꾸압 2023. 3. 26.

 

<설명>

(1) 아래 글을 참조하여 root 사용자 말고, 새로운 사용자를 만들어 권한을 주자.

https://printscanf.tistory.com/entry/Error-MySQL-Access-denied-for-user-useridlocalhost

 


 

(2) 해당 Rust 파일 디렉토리에 mysql 의존성을 추가

$ cargo add mysql

 


 

(3) 테이블 생성 및 Data 적재 예시

use mysql::prelude::*;
use mysql::*;

fn main() -> Result<()> {
    // Set up a new database connection
    let url = "mysql://id:pswd@localhost:3306/moto";
    let pool = Pool::new(url)?;

    // Create a new table named "test"
    let mut conn = pool.get_conn()?;
    conn.query_drop(
        r#"
        CREATE TABLE IF NOT EXISTS test (
            idX INT UNSIGNED NOT NULL AUTO_INCREMENT,
            content TEXT,
            PRIMARY KEY(idx)
        )
        "#,
    )?;

    // Insert sample data into the "test" table
    let sample_data = vec![
        ("Hello, world!"),
        ("This is a sample text."),
        ("Lorem ipsum dolor sit amet"),
    ];

    for data in sample_data {
        conn.exec_drop(
            r#"INSERT INTO test (content) VALUES (?)"#,
            (data,)
        )?;
    }

    Ok(())
}

 


 

<참조 1> https://chat.openai.com/chat

<참조 2>

 

 

댓글