使用带有Ruby的PG gem在insert语句中选择多个值

时间:2014-06-02 23:56:44

标签: sql ruby pg

你们可以帮我解决这个问题。 如果我直接在postgresql数据库中使用这个db查询它可以正常工作,但是当在Ruby中使用PG gem时,它希望我在数组中有6个值,但是我想从SELECT语句中获取这些值。

我收到的错误消息是:

ERROR:  bind message supplies 1 parameters, but prepared statement "statement2" requires 6 (PG::ProtocolViolation)

这里是使用PG gem的Ruby中的代码。

conn.prepare('statement2', 'INSERT INTO client_results (client_type, distance, hostname, serial_number, rssi, txrate) VALUES ($1, $2, $3, $4, $5, $6)')
conn.exec_prepared('statement2', ["SELECT client_type, distance_in_ft, hostname, serial_number, -65, 224 FROM test_clients WHERE eth_ipv4 = 192.168.0.1"])

实际运行的SQL如下所示:

INSERT INTO client_results (client_type, distance, hostname, serial_number, rssi, txrate) SELECT client_type, distance_in_ft, hostname, serial_number, -65, 224 FROM test_clients WHERE eth_ipv4 = '192.168.0.1';

1 个答案:

答案 0 :(得分:1)

res = conn.exec("SELECT client_type, distance_in_ft, hostname, serial_number, -65, 224 FROM test_clients WHERE eth_ipv4 = 192.168.0.1").first

conn.prepare('statement2', 'INSERT INTO client_results (client_type, distance, hostname, serial_number, rssi, txrate) VALUES ($1, $2, $3, $4, $5, $6)')
conn.exec_prepared('statement2', res.values)

或者只是按原样运行查询:

conn.exec("INSERT INTO client_results (client_type, distance, hostname, serial_number, rssi, txrate) SELECT client_type, distance_in_ft, hostname, serial_number, -65, 224 FROM test_clients WHERE eth_ipv4 = '192.168.0.1'")