我正在使用rails 3,我需要在我的一个迁移中执行原始sql,我需要使用预准备语句来执行它,因为它是避免由于单个,语句等引起的问题的最佳方法。有没有办法可以在一个prepare语句中执行多个sql语句。我正在使用PostgreSQL作为我的数据库
这是我尝试的代码
CONN = ActiveRecord::Base.connection.raw_connection
sql = %Q[
INSERT INTO table1
(
name,
email,
phone,
created_at,
updated_at
)
VALUES
(
$1,
$2,
$3,
current_timestamp,
current_timestamp
);
UPDATE table2
SET column_1 = $1
WHERE id = $4;
UPDATE contacts SET
column_2 = $2
WHERE id = $4
]
CONN.prepare('insert_and_update', sql)
CONN.exe_prepared('insert_and_update', [
name,
email,
phone,
customer.id
])
但我收到错误
cannot insert multiple commands into a prepared statement
答案 0 :(得分:3)
将其变为单个命令:
with i as (
insert into table1 (
name,
email,
phone,
created_at,
updated_at
) values (
$1,
$2,
$3,
current_timestamp,
current_timestamp
), u as (
update table2
set column_1 = $1
where id = $4
)
update contacts
set column_2 = $2
where id = $4
;