How to use sqlx transactions

use sqlx::mysql::MySqlPoolOptions;

#[tokio::main]
async fn main() {
    let pool = get_client(&TidbConfig {
        host: "127.0.0.1".to_string(),
        user: "root".to_string(),
        pwd: "123456".to_string(),
        db_name: "shop".to_string(),
        port: 3306,
    })
    .await
    .unwrap();

    App::new(pool).run().await
}

struct App {
    client: sqlx::Pool<sqlx::MySql>,
}
impl App {
    fn new(client: sqlx::Pool<sqlx::MySql>) -> Self {
        Self { client }
    }
    async fn run(&self) {
        let mut tx = self.client.begin().await.unwrap();

        let sql_data = vec!["1", "7493989779944565348", "10000"];
        let mut info = sqlx::query(
            "SELECT * FROM `company` WHERE `status` = ? AND `id` = ? AND `account_id` = ?",
        );
        for item in sql_data {
            info = info.bind(item);
        }
        let res = info.execute(&mut tx).await.unwrap();
        println!("-----{:#?}", res);

        tx.commit().await.unwrap();

        tokio::select! {
            _ = tokio::signal::ctrl_c() => {},
        }
    }
}

async fn get_client(c: &TidbConfig) -> Result<sqlx::Pool<sqlx::MySql>, sqlx::Error> {
    let url = format!(
        "mysql://{}:{}@{}:{}/{}",
        c.user, c.pwd, c.host, c.port, c.db_name
    );
    let pool = MySqlPoolOptions::new().connect(&url).await?;
    Ok(pool)
}

struct TidbConfig {
    host: String,
    user: String,
    pwd: String,
    db_name: String,
    port: u16,
}

Report an error:

let res = info.execute(&mut tx).await.unwrap();
                                                 ^^^^^ the trait `Executor<'_>` is not implemented for `&mut Transaction<'_, MySql>`

You need to dereference the Transaction to get a Connection. Try execute(&mut *tx) instead of execute(&mut tx).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.