# This ruby script exctracts all information from a given database # and builds insert statements. Think if it as a flat file backup of # the database. require 'dbi' tables = "table_to_backup1", "table_to_backup2" data = Array.new dbh = DBI.connect("DBI:Mysql:my_db", "username", "psswd" ) tables.each{ |table| str = "SELECT * FROM #{table};" sth = dbh.prepare( str ) sth.execute # Step through each result, build insert statement while row=sth.fetch insert = "INSERT INTO #{table} VALUES(" first = true row.each{ |val| if val.nil? insert << ", null" else val = "#{val}" val.gsub!( /"/, "\\\"" ) first == true ? insert << "\"#{val}\"" : insert << ",\"#{val}\"" end first = nil } insert << ");" data.push insert end } dbh.disconnect data.each_index{ |i| puts data[i] }