简体   繁体   English

Rails MySQL临时表错误

[英]Rails MySQL Temporary Table Error

I am attempting to build a temporary table in rails given the action defined below: 考虑到以下定义的操作,我试图在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

In MySQL workbench the query executes fine, but when attempting to access this action through the route: http://localhost:3000/testCreate/70/(101),(102) the error appears below as: 在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

How can I prevent this error from occurring? 如何防止发生此错误?

Pass one valid sql query ActiveRecord::Base.connection.execute method. 传递一个有效的sql查询ActiveRecord::Base.connection.execute方法。 You are passing a set of sql queries and expecting it to work in one call. 您正在传递一组sql查询,并希望它可以在一个调用中工作。

The following should work: 以下应该工作:

create_tmp_table = 'CREATE TEMPORARY TABLE test (
          location varchar(10)
          );

 ActiveRecord::Base.connection.execute(create_tmp_table)

Documentation : http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute 文档: http : //api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM