2016-02-28 69 views
0

我有一個基本的變化DB/seeds.rb,一個單行,取出一個SQL文件:耙分貝:種子失敗,錯誤消息Mysql2 ::錯誤:您在您的SQL語法錯誤

ActiveRecord::Base.connection.execute(IO.read("db/load.sql")) 

而且load.sql文件的內容是這樣的:

BEGIN; 
INSERT INTO cities (id, name, created_at, updated_at) VALUES 
(1, 'Goleta', now(), now()), 
(2, 'Santa Barbara', now(), now()), 
(3, 'Montecito', now(), now()), 
(4, 'Summerland', now(), now()), 
(5, 'Carpinteria', now(), now()), 
(6, 'La Conchita', now(), now()); 
END; 

當運行命令

rake db:seed 

我收到此錯誤:

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 'INSERT INTO cities (id, name, created_at, updated_at) VALUES 
(1, 'Goleta', now()' at line 3 

我能夠在沒有任何錯誤的情況下從mysql控制檯執行相同的插入語句。 我在這裏做錯了什麼?

這裏是只含有2語句和第一個與有關語法相同的錯誤後未能於本文章的開頭髮送的文件load.sql一個新版本:

delete from stores_tacos; 
INSERT INTO cities (id, name, created_at, updated_at) VALUES 
(1, 'Goleta', now(), now()), 
(2, 'Santa Barbara', now(), now()), 
(3, 'Montecito', now(), now()), 
(4, 'Summerland', now(), now()), 
(5, 'Carpinteria', now(), now()), 
(6, 'La Conchita', now(), now()); 

回答

1

你爲什麼不做到這一點使用值的散列和良好的老ActiveRecord類? ActiveRecord的重點在於保護您免受SQL攻擊。

+0

經過10年的Oracle和3年的Postgres,我不需要任何SQL保護。只是瞭解與MySQL的差異。 –

+0

好的。首先,我的道歉。我並不是說'保護你'不是爲了侮辱你的SQL技能或經驗。老實說。我相信這是一個不常見的觀點,即AR的好處之一是,在Rails和底層dB之間創建抽象層時,它可以代表您處理某些dB特定的特性。這就是我'保護你'的意思。所以,再次抱歉。 – jvillian

+0

不用擔心,我是老後端的傢伙慢慢地移動到前端:)我編輯的問題提供一個load.sql文件,只有語句刪除和插入。刪除被提取,但是當達到插入時出現錯誤。也許「;」不是這些陳述之間的正確分隔符? –

3

刪除BEGINEND令牌。

此令牌被存放在存儲過程觸發器或事件中。

BEGIN ... END syntax is used for writing compound statements, which can appear within stored programs (stored procedures and functions, triggers, and events). A compound statement can contain multiple statements, enclosed by the BEGIN and END keywords. statement_list represents a list of one or more statements, each terminated by a semicolon (;) statement delimiter. The statement_list itself is optional, so the empty compound statement (BEGIN END) is legal.

來源: http://dev.mysql.com/doc/refman/5.7/en/begin-end.html

+0

它工作。可能需要在同一個文件中的語句?我添加了從城市刪除;在執行插入和刪除操作之前插入操作失敗並出現相同的錯誤。 –

+0

分享wole文件也許還有另一個錯誤。 –