简体   繁体   中英

Rails MySQL Temporary Table Error

I am attempting to build a temporary table in rails given the action defined below:

 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:

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. You are passing a set of sql queries and expecting it to work in one call.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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