使用Ruby导入Mysql数据

标签 mysql ruby mysqlimport

我正在使用 ruby​​ 将 csv 文件从前端导入到 mysql 中。 这是我的 Controller 代码


    require 'csv'

       def csv_import 
         @parsed_file=CSV::Reader.parse(params[:dump][:file])
         n=0
         @parsed_file.each  do |row|
         c=CustomerInformation.new
         c.job_title=row[1]
         c.first_name=row[2]
         c.last_name=row[3]
         if c.save
            n=n+1
            GC.start if n%50==0
         end
         flash.now[:message]="CSV Import Successful,  #{n} new records added to data base"
       end

This is my front end code.

<pre>
<% form_for :dump, :url=>{:controller=>"customer_informations", :action=>"csv_import"}, :html => { :multipart => true } do |f| -%>
 <table">
   <tr>
     <td>
      <label for="dump_file">
        Select a CSV File :
      </label>
     </td>
     <td >
       <%= f.file_field :file -%>
     </td>
   </tr>
   <tr>
     <td colspan='2'>
       <%= submit_tag 'Submit' -%>
     </td>
   </tr>
 </table>
<% end -%>
</pre>

现在我想要的是,我在数据库中有大约 30 列,csv 将包含 30 个列标题。另外,为了进行检查,我将使用 textfield 要求其中一列作为输入,这样 csv 表中就有 29 列。根据用户选择的选项,剂量 29 列将附加到文本框中所选的实体。

如有任何帮助,我们将不胜感激。

谢谢

最佳答案

如果您使标题与表格列相同,则您的代码应该简单如下:

CSV::foreach(filename, :headers => true) do |row|
  Model.new(row.to_hash).save
end

关于使用Ruby导入Mysql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098943/

相关文章:

mysql - 如何使用mysql数据库合并表?

ruby - RSpec 是否有可能期望两个表发生变化?

java - jsp中通过session访问时id太长。

php - Javascript 数组作为 BLOB(MIME 文本而非图像)保存到 mySQL 数据库中!

ruby - 卸载工头

ruby-on-rails - 用户使用RESTFUL身份验证登录后显示用户名?

windows - MYSQL.EXE 和 MYSQLINPORT.EXE 输入文件? ( Windows )

mysql - 将csv文件加载到mysql数据库中

mysql - 有什么方法可以将单引号内的 NULL 导入到 mySQL 中吗?

php - 我们何时/何地使用 PDO?