sqlite - 如何让 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。尝试了数百个其他的东西。:(
谢谢!
解决方案
可能还有几件事要尝试:
- 尝试
sqlite3 /home/ace/hello_world/test.db
双重验证数据库确实存在。确保tbl
在此处定义表.schema tbl
- 尝试使用单斜杠的数据库路径,即
sqlite:/home/ace/hello_world/test.db
- 最后尝试使用该
query
函数而不是macro
https://docs.rs/sqlx/0.3.5/sqlx/fn.query.html来查看它是否有效。
推荐阅读
- css - CSS:内部带有图像的锚点,保持纵横比并移动其图像
- swift - 使用 SwiftUI 创建 macOS 无窗口菜单栏应用程序
- r - R中的PLS - 对b侧加载混淆的潜在分类调节调解(帮助plssss?)
- javascript - window.localtion.href 打开错误的位置
- c# - 如何在端点下添加大文本(不是描述区域)
- jquery - 在剑道网格编辑按钮上打开cshtml单击
- python - 使用 Dask 数组时内存不足
- playframework - 如何将所有日志写入logback中的单个文件?
- python - 有没有办法在 python 中加速 odeint
- c# - PrintQueue.Refresh() 抛出错误,指出“调用线程无法访问此对象,因为不同的线程拥有它”