postgresql 错误:错误{ kind:ToSql(0),cause:Some(WrongType { postgres:Json,rust:“alloc::string::String”})}

yhxst69z  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(144)

我试图将JSON值插入到表中,但出现错误

async fn insert_values(client: &Client, user: Report) -> Result<(), Error> {
    // Serialize the user data to JSON
    let user_json = json!({
        "username": user.username,
        "gender": {
            "val": user.gender.val,
        },
    });
     let res = serde_json::to_string(&user_json ).unwrap();
    // Execute the SQL statement to insert values
    client
        .execute("INSERT INTO users (user_report) VALUES ($1)", &[&res])
        .await?;
    Ok(())
}

字符串
像这样Error: Error { kind: ToSql(0), cause: Some(WrongType { postgres: Json, rust: "alloc::string::String" }) }
下面是创建表函数

async fn create_table(client: &Client) -> Result<(), Error> {
    // Define the SQL statement to create a table if it doesn't exist
    let command = r#"
        CREATE TABLE IF NOT EXISTS users (
            id SERIAL PRIMARY KEY,
            user_report JSONB
        )"#;

    // Execute the SQL statement to create the table
    client.execute(command, &[]).await?;
    Ok(())
}


和Cargo.toml

[dependencies]
serde = {version = "1.0.164", features=["derive"]}
serde_json = "1.0.103"
tokio-postgres = [version = "0.7.10", features= ["with-serde_json-1"]]
tokio = { version = "1", features = ["full"] }


输出错误是Error: Error { kind: ToSql(0), cause: Some(WrongType { postgres: Json, rust: "alloc::string::String" }) },代码端编译没有任何错误,但在posgre本身出现一些这种错误

y0u0uwnf

y0u0uwnf1#

查看trait implementation,我看到trait ToSql是为serde_json Value enum实现的,而不是String。
如果你有一个实现Serialize的结构体,你可以使用serde_json::to_value(...)将它序列化为Value。
您可以跳过序列化到String并直接传递Value:

async fn insert_values(client: &Client, user: Report) -> Result<(), Error> {
    // Serialize the user data to JSON
    let user_json = json!({
        "username": user.username,
        "gender": {
            "val": user.gender.val,
        },
    });
    // Execute the SQL statement to insert values
    client
        .execute("INSERT INTO users (user_report) VALUES ($1)", &[&user_json])
        .await?;
    Ok(()
}

字符串

xqk2d5yq

xqk2d5yq2#

实际上,如果功能标志with-serde_json-1被激活,看起来Json是不必要的。因此,我建议使用@pr0gramista的答案,它稍微简洁一些。
tokio-postgres有一个structJson,隐藏在功能标志with-serde_json-1后面。

use tokio_postgres::types::Json;

async fn insert_values(client: &Client, user: Report) -> Result<(), Error> {
    // Serialize the user data to JSON
    let user_json = Json(json!({ // <-- `Json` can be bound into SQL.
        "username": user.username,
        "gender": {
            "val": user.gender.val,
        },
    }));
    // Execute the SQL statement to insert values
    client
        .execute("INSERT INTO users (user_report) VALUES ($1)", &[&user_json])
        .await?;
    Ok(()
}

字符串
我使用以下依赖项

[dependencies]
serde = "1.0.192"
serde_json = "1.0.108"
tokio = { version = "1.33.0", features = ["full"] }
tokio-postgres = { version = "0.7.10", features = ["with-serde_json-1"] }

相关问题