Archive for October, 2010

extract files from database

October 18, 2010

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.

Advertisements