2015-04-02 56 views
0

在MySQL中,我可以運行:如何在Ruby/Rails中使用load命令和MySQL?

LOAD DATA LOCAL INFILE "/home/pt/test/bal.csv" INTO TABLE bal FIELDS 
TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '"' IGNORE 1 
LINES; 

然而,在我的Ruby程序:

str="LOAD DATA LOCAL INFILE "/home/pt/test/bal.csv" INTO TABLE bal 
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '"' 
IGNORE 1 LINES;" 

puts str 

dbh.query(str) 

輸出是:

LOAD DATA LOCAL INFILE "/home/pt/test/bal.csv" INTO TABLE bal FIELDS 
TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '"' IGNORE 1 
LINES; 

/home/pt/test/ptb.rb:34:in `query': Field separator argument is not what 
is expected; check the manual (Mysql::Error) 
from /home/pt/test/ptb.rb:34:in `<main>' 

有什麼不對的代碼?

+0

海峽= 「LOAD DATA LOCAL INFILE \」/家/ PT /測試/ bal.csv \」 INTO TABLE BAL FIELDS '''''''''''''''''''' IGNORE 1 LINES;「 試試這個會工作.. :) – 2015-08-24 11:55:57

回答

0

ENCLOSED BY ' \"'

str="LOAD DATA LOCAL INFILE \"/home/pt/test/bal.csv\" INTO TABLE bal FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES;" 

刪除空格您還可以找到有用的%Q[]Ruby syntax。它的""模擬,但你不需要逃避"裏面的字符串:

str=%Q[LOAD DATA LOCAL INFILE "/home/pt/test/bal.csv" INTO TABLE bal FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;] 
+0

你試過%Q []語法嗎? – 2015-04-02 10:14:23

+0

我已經做了,但它不工作的主要錯誤是:字段分隔符參數不是預期的;請檢查/home/pt/test/ptb.rb:34:in' – 2015-04-02 10:17:26

+0

中的手冊(Mysql :: Error)是否可以在不做任何更改的情況下複製並粘貼此代碼:dbh.query%Q [LOAD DATA LOCAL INFILE「/ home/pt/test/bal.csv「INTO TABLE bal FIELDS TERMINATED BY','ENCLOSED BY''''TERMINATED BY'\ n'IGNORE 1 LINES;] – 2015-04-02 10:21:32