Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a binary file in an sql database?

Tags:

java

sql

I have a varbinary column we use to store excel files. I need to update this column with the contents of a different xls file that is currently on my filesystem.

Given a java.sql.Connection, how should I update the row?

We are using sql server 2005.

like image 975
Ben Noland Avatar asked May 13 '09 15:05

Ben Noland


2 Answers

I ended up doing the following:

PreparedStatement st = conn.prepareStatement("update MyTable set binaryData = ? where id= 9");
st.setBinaryStream(1, new FileInputStream(file), (int)file.length());
st.execute();
like image 175
Ben Noland Avatar answered Sep 29 '22 08:09

Ben Noland


Using a java.util.Connection and the correct SQL you could create an appropriate java.sql.PreparedStatement (I don't use SQL Server, so you'd be better writing the SQL yourself).

You can create a java.sql.Blob using the byte data read from your xls file.

Call .setBlob(Blob) on your PreparedStatement and then execute it.

I didn't write the code for you, but that should be the basics.

like image 36
Kurley Avatar answered Sep 29 '22 06:09

Kurley