如何使用rust sqlx创建SQLite数据库



我正在尝试从rusqlite =>sqlx .

rusqlite打开连接调用SQLite::open,并创建db文件。以下作品:

use rusqlite::Connection;
Connection::open(db_filename)

但是,我遵循sqlx端的文档(https://github.com/launchbadge/sqlx#connecting),它们立即引导我创建一个池:

use sqlx::sqlite::{SqlitePoolOptions};
SqlitePoolOptions::new()
.max_connections(1)
.connect(&format!("sqlite://{}", db_filename))
.await
.map_err(|err| format!("{}nfile: {}", err.to_string(), db_filename))?;

实际上产生Result<_, String>消息

Error: "error returned from database: unable to open database filenfile: /path/to/my.db"

我不清楚在sqlx世界中如何在第一次启动时实际编写这些db文件。

提示?

我在他们的问题跟踪器中发现了一个问题,您可以在文件名上使用?mode=rwc查询样式参数。

https://github.com/launchbadge/sqlx/issues/1114 issuecomment - 827815038

添加查询解决了问题。

您还可以将SqliteConnectOptions与Pool::connect_with结合使用,并使用较新版本的sqlx。

use sqlx::{sqlite::SqliteConnectOptions, Error, SqlitePool};
use std::{future::Future, path::Path};
async fn connect(filename: impl AsRef<Path>) -> impl Future<Output = Result<SqlitePool, Error>> {
let options = SqliteConnectOptions::new()
.filename(filename)
.create_if_missing(true);
SqlitePool::connect_with(options)
}

SqliteConnectOptions非常灵活,支持许多有用的选项,如加载扩展。

最新更新