how to read a file and insert it into a mysl blob field

J

Jochen Kaechelin

How can I read a localy stored file and insert it into a mysal blob
field?

Thanx
 
7

7stud --

Jochen said:
How can I read a localy stored file and insert it into a mysal blob
field?


require 'mysql'

begin
dbh = Mysql.real_connect('localhost', 'username', 'passwd',
'database')

data = File.read('data.txt') #get the data out of the file
data = dbh.escape_string(data) #escape any quotes in the data

dbh.query("
INSERT INTO table_name (char_field, int_field, tinyblob_field)
VALUES
('apple', 3, '#{data}')
")

result = dbh.query("SELECT * FROM table_name")
while row = result.fetch_row do
printf "%s, %s, %s\n", row[0], row[1], row[2]
end

result.free

rescue Mysql::Error => e
puts "Error code: #{e.errno}"
puts "Error message: #{e.error}"
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?('sqlstate')
ensure
dbh.close if dbh
end
 
7

7stud --

Just to be clear:

1) I am assuming 'mysl' and 'mysal' should be 'mysql'.

2) The field names char_field, int_field, tinyblob_field in the
following code:

dbh.query("
INSERT INTO table_name (char_field, int_field, tinyblob_field)
VALUES
('apple', 3, '#{data}')
")

have no significance--those names should be whatever you named your
fields in your database, e.g. name, id, data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top