如何在带有rust-postgres的预处理语句中选择动态表格?

时间:2016-05-04 16:14:18

标签: database postgresql rust

我在Rust中创建一个软件来从API收集数据并将其存储在PostgreSQL数据库中。

我有一个线程负责执行SQL查询和存储数据。为此,我使用了防锈箱。

我的数据库设置为具有不同乐器的不同表格。我试图用动态表名和动态值准备一个单一语句。这是我准备好的声明的代码:

let dburl = "postgres://user:pw@localhost/dbname";
let dbconn = Connection::connect(dburl, SslMode::None);
if dbconn.is_err() {
    println!("ERROR || Generic: Could not connect to postgres DB: {}",
             dbconn.unwrap_err());
    drop(receiver);
    return;
}
let dbconn = dbconn.unwrap();
let stmt = dbconn.prepare("INSERT INTO $1 (timestmp, hours, minutes, seconds, nanoseconds, \
                           ask, bid, weekday, status) VALUES ($2::varchar, $3::int, $4::int, \
                           $5::int, $6::int, $7, $8, $9, $10::bool)");
if stmt.is_err() {
    println!("ERROR || Generic: Failed to prepare SQL statement: {}",
             stmt.unwrap_err());
    drop(receiver);
    return;
}
let stmt = stmt.unwrap();
let mut instr: String = "scheme.".to_owned();

loop {
    let msg = receiver.recv();
    if msg.is_err() {
        break; // no more sender attached to channel
    }
    let msg = msg.unwrap();
    instr.push_str(&msg.instrument);
    let stmt_res = stmt.execute(&[&msg.timestmp,
                                  &msg.hours,
                                  &msg.minutes,
                                  &msg.seconds,
                                  &msg.nanoseconds,
                                  &msg.ask,
                                  &msg.bid,
                                  &msg.weekday,
                                  &msg.status]);
    if stmt_res.is_err() {
        println!("ERROR || Generic: Failed to execute prepared SQL statement: {}",
                 stmt_res.unwrap_err());
        drop(receiver);
        return;
    }
    let stmt_res = stmt_res.unwrap();
    println!(">> {} line affected by SQL query.", stmt_res);
    let instr: String = "scheme.".to_owned();
}

这会导致以下错误:

Error reported by Postgres: ERROR: syntax error at or near "$1"

我尝试使用$1::regclass,因为我认为my syntax is correct

如果这不可行或不易实现,我也考虑过这些选项:

  1. 为所有不同的工具准备陈述
  2. 将一张桌子中的所有乐器与另一个乐器'乐器合并。 (不是首选)
  3. 但这种动态解决方案将是首选。

0 个答案:

没有答案