首页 > 解决方案 > 如何让 Rust sqlx sqlite 查询工作?

问题描述

main.rs:

#[async_std::main]
async fn main() -> Result<(),sqlx::Error> {
    use sqlx::Connect;
    let mut conn = sqlx::SqliteConnection::connect("sqlite:///home/ace/hello_world/test.db").await?;
    let row = sqlx::query!("SELECT * FROM tbl").fetch_all(&conn).await?;
    println!("{}{}",row.0,row.1);
    Ok(())
}

货物.toml:

[package]
name = "hello_world"
version = "0.1.0"
authors = ["ace"]
edition = "2018"

[dependencies]
async-std = {version = "1", features = ["attributes"]}
sqlx = { version="0.3.5", default-features=false, features=["runtime-async-std","macros","sqlite"] }

bash 会话:

ace@SLAB:~/hello_world$ sqlite test.db
SQLite version 2.8.17
Enter ".help" for instructions
sqlite> create table tbl ( num integer, chr varchar );
sqlite> insert into tbl values (1,'ok');
sqlite> .quit
ace@SLAB:~/hello_world$ pwd
/home/ace/hello_world
ace@SLAB:~/hello_world$ export DATABASE_URL=sqlite:///home/ace/hello_world/test.db
ace@SLAB:~/hello_world$ cargo run
   Compiling hello_world v0.1.0 (/home/ace/hello_world)
error: failed to connect to database: file is not a database
 --> src/main.rs:8:12
  |
8 |     let row = sqlx::query!("SELECT * FROM tbl").fetch_all(&conn).await?;
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

error: could not compile `hello_world`.

To learn more, run the command again with --verbose.
ace@SLAB:~/hello_world$ rustc --version
rustc 1.44.0 (49cae5576 2020-06-01)
ace@SLAB:~/hello_world$ uname -r
5.4.0-33-generic
ace@SLAB:~/hello_world$ cat /etc/os-release | head -2
NAME="Ubuntu"
VERSION="20.04 LTS (Focal Fossa)"
ace@SLAB:~/hello_world$ 

还尝试将 DATABASE_URL “sqlite::memory:”(在环境变量和 main.rs 中)与系统表“sqlite_master”一起使用。得到不同的错误:

error[E0277]: the trait bound `&sqlx_core::sqlite::connection::SqliteConnection: sqlx_core::executor::RefExecutor<'_>` is not satisfied

...但它一定已经成功了,因为当我将表名“Xsqlite_master”与内存数据库一起使用时,它抱怨说没有这样的表。

尝试了“sqlite://home”(etc) 和其他斜杠数,从 0 到 4。尝试了数百个其他的东西。:(

谢谢!

标签: sqliterust

解决方案


可能还有几件事要尝试:

  1. 尝试sqlite3 /home/ace/hello_world/test.db双重验证数据库确实存在。确保tbl在此处定义表.schema tbl
  2. 尝试使用单斜杠的数据库路径,即sqlite:/home/ace/hello_world/test.db
  3. 最后尝试使用该query函数而不是macro https://docs.rs/sqlx/0.3.5/sqlx/fn.query.html来查看它是否有效。

推荐阅读