Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a file into sql-server via tiny_tds?

In a data importing script:

 client = TinyTds.Client.new(...)
 insert_str = "INSERT INTO [...] (...) VALUE (...)"
 client.execute(insert_str).do

So far so good.

However, how can I attach a .pdf file into the varbinary field (SQL Server 2000)?

like image 920
ohho Avatar asked Apr 09 '26 03:04

ohho


1 Answers

I've recently had the same issue and using activerecord was not really adapted for what I wanted to do...

So, without using activerecord:

client = TinyTds.Client.new(...)
data = "0x" + File.open(file, 'rb').read.unpack('H*').first
insert_str = "INSERT INTO [...] (...) VALUE (... #{data})"
client.execute(insert_str).do

To send proper varbinary data, you need to read the file, convert it to hexadecimal string with unpack('H*').first and prepend '0x' to the result.

like image 130
merlin Gaillard Avatar answered Apr 10 '26 18:04

merlin Gaillard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!