鉴于下面定义的操作,我正在尝试在 Rails 中构建临时表:
def testCreate
insert = 'CREATE TEMPORARY TABLE test (
location varchar(10)
);
CREATE TEMPORARY TABLE test2 (
campaign varchar(10)
);
INSERT INTO test
VALUES' + params[:insert_location_csv].to_s + ';
INSERT INTO test2
VALUES(' + params[:campaign_id].to_s + ');
INSERT INTO campaign_locations(campaign_id, location_id, created_at, updated_at)
select
a.campaign as campaign_id
,b.location as location_id
,NOW() as created_at
,NOW() as updated_at
from test2 a
cross join test b'
ActiveRecord::Base.connection.execute(insert)
end
在 MySQL 工作台中,查询执行正常,但是当尝试通过路由访问此操作时:http://localhost:3000/testCreate/70/(101),(102)
错误如下所示:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TEMPORARY TABLE test2 ( campaign varchar(10) ); INSERT' at line 5: CREATE TEMPORARY TABLE test ( location varchar(10) ); CREATE TEMPORARY TABLE test2 ( campaign varchar(10) ); INSERT INTO test VALUES(101),(102); INSERT INTO test2 VALUES(70); INSERT INTO campaign_locations(campaign_id, location_id, created_at, updated_at) select a.campaign as campaign_id ,b.location as location_id ,NOW() as created_at ,NOW() as updated_at from test2 a cross join test b
如何防止此错误发生?
最佳答案
传递一个有效的 SQL 查询 ActiveRecord::Base.connection.execute
方法。您正在传递一组 SQL 查询并期望它在一次调用中工作。
以下应该有效:
create_tmp_table = 'CREATE TEMPORARY TABLE test (
location varchar(10)
);
ActiveRecord::Base.connection.execute(create_tmp_table)
关于mysql - Rails MySQL 临时表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322770/