This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HOW TO Upload files to db (postgres) using java/jdbc

 
e_poncedeleon
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am new to this and i want to upload some files to my database but i simple can't figure out how to...can anyone give me an example on how to upload a file(binary data) using java and jdbc to my database...
Thank you
Eduardo
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34095
337
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eduardo,
Welcome to JavaRanch!

Uploading files to the database server is the same as uploading to any other machine. Then you can run the database import utility to get the files into the database.
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By "upload", do you mean to store it as a whole? If so, that's what BLOB type attribute are for. That's supported by the Statement and ResultSet classes, so if you have the file contents in your Java code, it shouldn't be too difficult. What do you have so far?

As an aside, storing binary file contents in a DB isn't always the best way to do it. Have you considered storing the file in the file system, and only keeping the path to the file in the DB?
 
Ramesh Etta
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the sample code

import java.io.*;
import java.sql.*;
public class ImageStoreDatabase{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
("jdbcracle:thin:@localhost:1521:sid","scott","tiger");
PreparedStatement pstmt=con.prepareStatement("insert into image values
(?,?)");
FileInputStream fis=new FileInputStream("file name");
pstmt.setInt(1,21);
pstmt.setBinaryStream(2,fis,fis.available());
pstmt.executeUpdate();
}catch(Exception e){}
finally{
//pstmt.close();
}
}
}
and the table of the structure goes like this
create table image(id number(5),image blob);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic