Skip to content

Instantly share code, notes, and snippets.

@tuxdna
Created February 4, 2013 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxdna/4706365 to your computer and use it in GitHub Desktop.
Save tuxdna/4706365 to your computer and use it in GitHub Desktop.
A Ruby script to add binary documents into a MySQL database
#!/usr/bin/ruby
# File name: insert-mysql.rb
# Usage:
# $ ruby insert-mysql.rb /path/to/file.pdf "description of file"
require 'mysql'
require 'mime/types'
if ARGV.length < 2 then
puts "Insufficient arguments"
exit 1
end
puts "Creating connection..."
conn = Mysql::new("localhost", "binary_user", "binary_password", "binary_files")
filepath = ARGV[0]
filetype = MIME::Types.type_for(filepath).first.content_type
description = ARGV[1]
data_file = File.new(filepath, "r")
filename = File.basename(filepath)
filesize = data_file.size
bin_data = data_file.read
puts "Running insert query..."
query = "INSERT INTO tbl_files (description, bin_data, filename, filesize, filetype) VALUES ( ?, ?, ?, ?, ?)"
begin
pst = conn.prepare(query)
pst.execute(description, bin_data, filename, filesize, filetype)
rescue Mysql::Error => e
puts e
ensure
conn.close if conn
pst.close if pst
end
puts "DONE..."
def read_results(conn)
puts "Fetching results for query..."
res = conn.query("select * from tbl_files");
res.each do |row|
col1 = row[0]
col2 = row[1]
end
puts "DONE"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment