【发布时间】:2020-05-09 15:36:27
【问题描述】:
contacts 的数据结构为HashMap,我使用PostgreSQL 客户端-rust-postgres 将contact 的键和值插入到表中,然后我想从表中进行选择。以下是我到目前为止所尝试的。我需要帮助来编写正确的语法。
use postgres::{Client, NoTls};
use std::collections::HashMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = Client::connect("host=127.0.0.1 user=postgres", NoTls)?;
client.simple_query("
DROP TABLE
IF EXISTS following_relation;
")?;
client.simple_query("
CREATE TABLE following_relation (
id SERIAL NOT NULL PRIMARY KEY,
relation JSON NOT NULL
)
")?;
let mut contacts = HashMap::new();
let mut v: Vec<String> = Vec::new();
v = vec!["jump".to_owned(), "jog".to_string()];
contacts.insert("Ashley", v.clone());
for (name, hobby) in contacts.iter() {
// 1. How to write sql statement with parameters?
client.execute(
"INSERT INTO following_relation(relation)
VALUE ('{"name" : $1, "hobby" : $2}')",
&[&name, &hobby],
)?;
}
for row in client.query("SELECT id, relation FROM following_relation", &[])? {
// 2. How to read from parse the result?
let id: i32 = row.get(0);
let relation = row.get(1);
//println!("found person: {} {} {:?}", id, relation["name"], relation["hobby"]);
}
Ok(())
}
我得到了提示
- 正如错误消息所说,您的查询有 VALUE,但它必须是 VALUES。
- 查询参数不能插入到字符串中。您应该在 Rust 中构建对象,并在插入时使用 https://docs.rs/postgres/0.17.0/postgres/types/struct.Json.html 包装类型。
我不知道如何在这里申请pub struct Json<T>(pub T);。
如何构建函数execute所需的query?
pub fn execute<T: ?Sized>(
&mut self,
query: &T,
params: &[&(dyn ToSql + Sync)]
) -> Result<u64, Error>
where
T: ToStatement,
已更新,我尝试使用更简短的代码示例
use postgres::{Client, NoTls};
use postgres::types::Json;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct relations {
name : String,
hobby: Vec<String>
}
pub struct Json<T>(pub T);
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = Client::connect("host=127.0.0.1 user=postgres", NoTls)?;
client.simple_query("
DROP TABLE
IF EXISTS following_relation;
")?;
client.simple_query("
CREATE TABLE following_relation (
id SERIAL PRIMARY KEY,
relation JSON NOT NULL
)
")?;
let rel = relations {
name: "czfzdxx".to_string(),
hobby: vec![
"basketball".to_string(),
"jogging".to_string()
],
};
client.execute(
r#"INSERT INTO following_relation(relation)
VALUE ($1)"#,
&[&Json(&rel)]
)?;
Ok(())
}
我明白了
error[E0432]: unresolved import `postgres::types::Json`
【问题讨论】:
-
我不能让它工作,这是我得到的,所以也许你可以从那里拿起
-
也是 cargo.toml gist.github.com/pbn4/5b6dadc9ca31e2aed91b3a391ecd2b98
-
@pbn 我马上去看看。
标签: postgresql rust