extract files from database

What the heck, may as well use this site a little bit.  Actually kind of forgot it was here.

Recently I was involved in rebuilding a client’s site that had previously used some old CMS system (in Java, source code not to be found) of our company’s, with our new one (in Ruby On Rails).  I needed to reuse some of the original images.  Turns out the old tool kept images and various other files used on the site in the MySQL database, as BLOB objects.  I’ll never understand why people do this.

I came up with this quickie little script to pull the files out of the database and save then as good old fashioned files.  Thought I’d share it.

#!/usr/bin/env ruby
require 'rubygems'
require 'mysql'
require 'fileutils'
include FileUtils
mkdir ('files')
db = Mysql.new('server', 'user', 'password', 'database')
db.query("select * from table_with_blobs_in_it") do |res|
  res.each_hash do |rec|
    File.open("files/#{rec['filename_column']}", 'w') do |f|
      f.write(rec['blob_column'])
    end
  end
end

Yay.

One Response to “extract files from database”

  1. warrenosborne81450 Says:

    Very great report, very clear, deep analyze and easy to understand.nThank for your share. Click http://link.mx/hool081945

Leave a reply to warrenosborne81450 Cancel reply