0

我将 Rails 3.1.0 和 Ruby 1.9.2 与 PostgreSQL 一起使用。我想从大文件(~300mb)中获取数据并将其放入数据库。在这里我使用交易:

File.open("./public/data_to_parse/movies/movies.list").each do |line|
  if line.match(/\t/)
    title = line.scan(/^[^\t(]+/)[0]
    title = title.strip if title 
    year = line.scan(/[^\t]+$/)[0]
    year = year.strip if year
    movie = Movie.find_or_create(title, year)
    temp.push(movie) if movie
    if temp.size == 10000
      Movie.transaction do
        temp.each { |t| t.save }
      end    
       temp =[]
    end
  end
end

但我想通过原始 SQL 使用批量插入来提高性能:

temp.push"(\'#{title}\', \'#{year}\')" if movie
  if temp.size == 10000
   sql = "INSERT INTO movies (title, year) VALUES #{temp.join(", ")}" 
   Movie.connection.execute(sql)
   temp =[]
  end
end

但我有这个错误“不兼容的字符编码:ASCII-8BIT 和 UTF-8”。当我使用 activerecord 时,一切正常。文件包含诸如德语变音符号之类的字符。我从这里尝试了所有 Rails 3 - (incompatible character encodings: UTF-8 and ASCII-8BIT):,但这对我没有帮助。

你知道它是从哪里来的吗?

谢谢,

4

1 回答 1

2

解决了。问题出在文件编码中。它们在 ISO_8859-1 中,我通过 iconv 将其转换为 UTF-8。

于 2011-10-25T05:10:52.597 回答