wood burning stoves*
The moose likes JDBC and the fly likes Inserting Files to Database. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Inserting Files to Database." Watch "Inserting Files to Database." New topic
Author

Inserting Files to Database.

Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
Hi there. I have a Java program which allows the user to select a File from there desktop.

I then want to save this in my database, where I have a column which is of type IMAGE.

My query is "INSERT INTO MYTABLE VALUES(199,'This is a file' , " + getByteArray(files.get(0)) + ")";

This does not work, is their a better way to do it?
Koen Aerts
Ranch Hand

Joined: Feb 07, 2012
Posts: 344

What DB are you using? You'll have to create a java.util.PreparedStatement and use something like setBlob() to set the binary contents for the image column.
Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
Its a SQL database. Using SQL Server.

Thanks will give it a try. Why does it only work with a prepared statement, do you have an example?
Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
I have got closer, but it does not seem to work.



Any help? Much needed!

The column is of type binary(50) where the stream is supposed to go.
Koen Aerts
Ranch Hand

Joined: Feb 07, 2012
Posts: 344

What is your issue/error... any details? Also, it's probably better to also specify the column names that you want to insert values into. For instance "INSERT INTO CAR (REG_NO, NOTE, IMG, CATEGORY, SOMETHING_ELSE) VALUES(?,?,?,?,?)".
Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
It was due to not having the column as varbinary(max) apparently. Thanks.
Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
I have one more question didn't think it was worth a thread.

Say I execute an update statement to insert a new row into a table, I immediately need to use the generated id of that row. How do I retrieve it seen as an update doesn't produce a result set?
Koen Aerts
Ranch Hand

Joined: Feb 07, 2012
Posts: 344

Something along the lines like this:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inserting Files to Database.
 
Similar Threads
Jar file for DB2 Connection?
how to get LastModified time of a file system file and webserver file
how to get LastModified time of a file system file and webserver file
how to get LastModified time of a file system file and webserver file
Defining Datasource in JBoss4.x