我尝试将 SQLx 与 SQLite 结合使用来:
我正在努力确定函数的事务参数应该是什么,以及如何在函数内使用事务。
唯一的官方示例我看到有关 PostgreSQL 并将其适配到 SQLite 不起作用。
ChatGPT 4 也未能给我一个有效的示例:
// sqlx = { version = "0.7.4", features = ["runtime-tokio-rustls", "sqlite"] }
// tokio = { version = "1.36.0", features = ["full"] }
use sqlx::sqlite::{SqlitePool, Sqlite};
use sqlx::{Pool, Transaction, Error};
async fn execute_query(tx: &mut Transaction<'_, Sqlite>) -> Result<(), Error> {
sqlx::query("INSERT INTO users (name) VALUES ('Alice')")
.execute(tx)
.await?;
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let pool: Pool<Sqlite> = SqlitePool::connect("sqlite::memory:").await?;
let mut tx = pool.begin().await?;
execute_query(&mut tx).await?;
tx.commit().await?;
Ok(())
}
产生此错误:
error[E0277]: the trait bound `&mut Transaction<'_, Sqlite>: Executor<'_>` is not satisfied
--> src\main.rs:9:18
|
6 | .execute(tx)
| ------- ^^ the trait `Executor<'_>` is not implemented for `&mut Transaction<'_, Sqlite>`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `Executor<'c>`:
<&'c mut SqliteConnection as Executor<'c>>
<&'c mut AnyConnection as Executor<'c>>
<&Pool<DB> as Executor<'p>>
.execute(&mut **tx)
我在没有传递可变引用的情况下得到了一个不同的错误。