Insertingand retrieving images in database using jdbc

i am new to jsp.i have to store and retrieve image files using oracle 8i.Then i have to display it using jsp.
my code for storing image is
package sample;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import java.sql.*;
import java.io.*;
import java.awt.image.*;
import java.awt.*;
public class storephoto{
public static void main(String[] args){
String filename = "C:/Documents and Settings/user/Desktop/five.gif";
Connection conn = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@10.1.4.228:1521:data","system","manager");
conn.setAutoCommit(false);
Statement st = conn.createStatement();
int b= st.executeUpdate("insert into bfiles values('"+filename+"', empty_blob())");
ResultSet rs= st.executeQuery("select * from bfiles for update");
rs.next();
BLOB blob=((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(2);
FileInputStream instream = new FileInputStream(filename);
System.out.println("instream="+instream);
OutputStream outstream = blob.getBinaryOutputStream();
System.out.println("outstream="+outstream);
int chunk = blob.getChunkSize();
System.out.println("chunk="+chunk);
byte[] buff = new byte[chunk];
int le;
while( (le=instream.read(buff)) !=-1)
System.out.println(le);
outstream.write(buff,0,le);
System.out.println(buff);
instream.close();
outstream.close();
conn.commit();
conn.close();
conn = null;
System.out.println("Inserted.....");
catch(Exception e){
System.out.println("exception"+e.getMessage());
e.printStackTrace();
}//catch
This code works fine & something gets stored in the buffer.but while rereiving nothing gets retreived.i cannot retrieve the image file
my code for retreiving is
package sample;
import java.sql.*;
import java.io.*;
import java.awt.*;
import oracle.sql.BLOB;
public class retphoto
public static void main(String a[])
String fileName ="C:/Documents and Settings/user/Desktop/five.gif";
try
Driver driver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(driver);
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@10.1.4.228:1521:data", "system", "manager");
File file = new File("C:/Documents and Settings/user/Desktop/sa1.gif");
FileOutputStream targetFile= new FileOutputStream(file); // define the output stream
PreparedStatement pstmt = con.prepareStatement("select filecontent from bfiles where filename= ?");
pstmt.setString(1, fileName);
ResultSet rs1 = pstmt.executeQuery();
rs1.next();
InputStream is = rs1.getBinaryStream(1);
System.out.println(is);
byte[] buff = new byte[1024];
int i = 0;
while ((i = is.read(buff)) != -1) {
System.out.println("hai");
System.out.println(i);
targetFile.write(buff, 0, i);
System.out.println("Completed...");
rs1.close();
is.close();
targetFile.close();
pstmt.close();
con.close();
catch(Exception e)
System.out.println(e);
}

Thanks for ur help:
another Q:
in my GUI i have a button called Insert. but can't update my database table unless i create textField(e.g Firstname, Surname..ect..), so that when I click Insert button in actionEvent it will bring up popup which have field name in which i am going to insert new records.
so what iam trying to say is, how iam going to tell the actionEvent to trigger this.
the following is my code
public void actionPerformed(ActionEvent event)
ExamResults exam= new ExamResults ();      
String studentId = studentTextField.getText();
if (event.getSource() == insert) //if insert is clicked
Thanks

Similar Messages

  • Store and retrieve image in database using WD Java

    Hi All,
    I have to store and retrieve an image in oracle database. I have gone through the below blog and forum...
    How to display an image, which is stored in a database?
    The specified item was not found.
    I am able to store image in byte format(oracle data type BLOB) and when i try to retrieve it i am not getting the image....Sorry for my poor technical knowledge.
    can some body help me, please......
    Regards,
    G.

    Hi,
    my code is working... I am able to upload and retrieve the image. But now I am getting the below exception...
    Exception from image insert>> java.sql.SQLException: Data size bigger than max size for this type: 6770
    Below is the code I am uing...
    ConnectDataBase condb=new ConnectDataBase();
        IWDMessageManager mgnr=wdComponentAPI.getMessageManager();
         IPrivateDBImageView.IVn_FileElement  fileelement =
                                  wdContext.nodeVn_File().getVn_FileElementAt(0);
                             IWDResource resource=wdContext.currentContextElement().getResource();
    InputStream in=resource.read(false);
    ByteArrayOutputStream bOut=new ByteArrayOutputStream();
                             int lenght=0;
                             byte part[]=new byte [ 50000 ];
                             while((lenght=in.read(part))!=-1)
                             bOut.write(part,0,lenght);     
              Statement  stmnt=null;
                   Connection con=null;
                   String strQuery=null;
                   String strProp_Details=null;
                   try {
                        con=condb.getConnection (mgnr);
                        stmnt=con.createStatement();
                   PreparedStatement pst=con.prepareStatement("insert into VMS_Image values(?,?,?)");
                        pst.setInt(1,4);
                        pst.setString(2,"srinu1234");
                        pst.setBytes(3,bOut.toByteArray());
                        pst.execute();
                        bOut.close();
                        in.close();
                        mgnr.reportSuccess("Inserted");
                   catch (SQLException e) {
         mgnr.reportException("SQLException from image insert>>"+e,false);
                   catch(Exception e)
                             mgnr.reportException("Exception from image insert>>"+e,false);     
                        finally
                        try
                        if(stmnt!=null)
                             stmnt.close();
                             stmnt=null;     
                        if(con!=null)
                             con.close();     
                             con=null;
                        catch(Exception e)
                             mgnr.reportException("Exception in Closing from image insert>>"+e,false);
    first I used byte of 101024, then 501024 and finally tried with byte of 50000. I am getting the above exception if the image size is more than 4kb....
    Regards,
    Srinivas.
    Edited by: srinivas sistu on Aug 1, 2008 2:26 PM
    Edited by: srinivas sistu on Aug 1, 2008 2:34 PM

  • Inserting Multiple Images into oracle database using JDBC

    I wanted to insert multiple images into database using JDBC by reading it from the file... and i am passing photos.txt(my text file) as an input parameter... I have inserted all the values into the database except for the image part... this is my content of photos.txt file and i have copied all the images into the folder
    *" C:\\photos "*
    *1,in1.jpg,108,19,in-n-out*
    *2,in2.jpg,187,21,in-n-out*
    *3,in3.jpg,308,41,in-n-out*
    *4,in4.jpg,477,52,in-n-out*
    *5,in5.jpg,530,50,in-n-out*
    and i want to store in1.jpg,in2.jpg,in3.jpg,in4.jpg,in5.jpg into the oracle databse using JDBC.... i have tried a lot using BLOB column.... and i have created my table as
    CREATE TABLE PHOTO(
    ID NUMBER NOT NULL PRIMARY KEY ,
    Name BLOB,
    X DOUBLE PRECISION,
    Y DOUBLE PRECISION,
    Tags VARCHAR2(40)
      try {                 // for restaurant System.out.println();System.out.println();System.out.println(); System.out.print("  Creating Statement for Photo...\n");             stmt2 = con.createStatement ();                       stmt2.executeUpdate("delete from PHOTO"); stmt2.executeUpdate("commit"); PreparedStatement stmt3 = con.prepareStatement ("INSERT INTO PHOTO VALUES (?, ?, ?, ?, ?)");             System.out.print("  Create FileReader Object for file: " + inputFileName1 + "...\n");             FileReader inputFileReader2 = new FileReader(inputFileName1);             System.out.print("  Create BufferedReader Object for FileReader Object...\n");             BufferedReader inputStream2  = new BufferedReader(inputFileReader2);             String inLine2 = null;                         String[] tokens; //            String[] imageFilenames = {"c:\\photos\\in1.jpg","c:\\photos\\in2.jpg","c:\\photos\\in3.jpg","c:\\photos\\in4.jpg","c:\\photos\\in5.jpg", //  "c:\\photos\\in6.jpg","c:\\photos\\in7.jpg","c:\\photos\\in8.jpg","c:\\photos\\in9.jpg","c:\\photos\\in10.jpg","c:\\photos\\arb1.jpg","c:\\photos\\arb2.jpg", //  "c:\\photos\\arb3.jpg","c:\\photos\\arb4.jpg","c:\\photos\\arb5.jpg","c:\\photos\\den1.jpg","c:\\photos\\den2.jpg","c:\\photos\\den3.jpg", //  "c:\\photos\\den4.jpg","c:\\photos\\den5.jpg","c:\\photos\\hop1.jpg","c:\\photos\\hop2.jpg","c:\\photos\\hop3.jpg","c:\\photos\\hop4.jpg","c:\\photos\\hop5.jpg"};               File file = new File("C:\\photos\\in1.jpg");            \\ ( Just for example  )           FileInputStream fs = new FileInputStream(file);                         while ((inLine2 = inputStream2.readLine()) != null) {               tokens= inLine2.split(",");             st2 = new StringTokenizer(inLine2, DELIM);                                                             stmt3.setString(1, tokens[0]);               stmt3.setBinaryStream(2, fs, (int)(file.length()));               stmt3.setString(3, tokens[2]);               stmt3.setString(4, tokens[3]);               stmt3.setString(5, tokens[4]);               stmt3.execute(); //execute the prepared statement               stmt3.clearParameters(); 
    As i am able to enter one image file by above code in1.jpg in to the oracle database.... but i am not able to insert all the image file in to the database.....do tell me what should i do.... and can you give me the example on the basis of the above code of mine...
    do reply as soon as possible..

    jwenting wrote:
    that depends. Putting the images in BLOBs prevents the file locations stored in the database from getting out of synch with the filesystem when sysadmins decide to reorganise directory structures or "archive" "old" files that noone uses anyway.True, but it really comes down to a business decision (cost-benefit analysis). If you have the bucks, the expertise, and the time, go with the Blobs, otherwise go with the flat files.

  • How to store and retrieve images from database...

    Hi All
    Anubody tell me plz how to store images in database using jsp.
    and how to retrieve tme.
    Plz reply...
    Anurag

    Exactly
    try the links below may be those might help u in store and retrieval any kind of file.
    http://www.mysqltalk.org/insert-blob-example-vt112861.html
    https://java.sun.com/j2se/1.5.0/docs/guide/jdbc/blob.html
    http://javaalmanac.com/egs/java.sql/GetBlob.html
    http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.jdbc.doc/jdbc142.htm
    and a dearly advice friend please query google b4 you post any query out here.

  • NCHAR issue with oracle database using JDBC adapter

    Hi,
    We have a requirement to develop an XI interface from FTP server(File adapter) to oracle database using JDBC adapter. In the oracle database table few fields are of type NCHAR/NVARCHAR. when we try to insert the character(A,B,c..) values into oracle table fields of type NCHAR/NVARCHAR, we are getting the following error message in the JDBC adapter audit log. IF we pass the numeric value to the same field, then we are able to insert the records successfully.
    Unable to execute statement for table or stored procedure. 'IPCSDD_DOWNLOAD_PROCESS' (Structure 'StatementName1') due to java.sql.SQLException: ORA-00904: "P": invalid identifier
    2010-10-19 22:29:59 Error JDBC message processing failed; reason Error processing request in sax parser: Error when executing statement for table/stored proc. 'IPCSDD_DOWNLOAD_PROCESS' (structure 'StatementName1'): java.sql.SQLException: ORA-00904: "P": invalid identifier
    2010-10-19 22:29:59 Error MP: Exception caught with cause com.sap.aii.af.ra.ms.api.RecoverableException: Error processing request in sax parser: Error when executing statement for table/stored proc. 'IPCSDD_DOWNLOAD_PROCESS' (structure 'StatementName1'): java.sql.SQLException: ORA-00904: "P": invalid identifier
    Please find the system information below.
    Oracle version- 10.2.4
    XI version - 3.0/ service pack 19
    JDBC driver- oracle.jdbc.driver.OracleDriver
    Please suggest.
    Thanks,
    Venkata
    Edited by: Venkata Narayana  Eepuri on Oct 21, 2010 12:10 AM

    Dear Venkata Narayana,
    Concerning the error, kindly go through the following note :
    731 - Collective note: ORA-00904
    follow the recommendations mentioned in that and please check if that helps.
    Best Regards
    Nishwanth

  • How to store images in database using java

    hii
    how to store images in database using java..........
    Message was edited by:
    naveennaga

    I asked a similar question once and the answer I got was - Don't.
    Instead, store the images on a drive somewhere and store the path in the database.
    But I'm no expert - that's just what I was told by someone who does this kind of stuff a lot.
    Hope that helps.

  • How to Connect Microsoft SQL 2000 database using JDBC

    Hi all..
    I want to connect Microsoft SQL 2000 database using JDBC. I want from initial steps also. (about JDBC driver & its installation)
    Thankz

    Just checkout the SQL Server JDBC Driver Documentation at the manfacturer's site: http://msdn2.microsoft.com/en-us/data/aa937724.aspx

  • How to eliminate inserting  Duplicate rows into database using JDBC Adapter

    File->Xi->JDBC
    In above Scenario if the file has two rows their values are identical, then how can we eliminated inserting  Duplicate rows into database using JDBC Adapter

    Database is a consumer of a SERVICE (SOA!!!!!!).
    Database plays a business system role here!!!!
    Mapping is part of an ESB service
    Adaptor is a technology adapted to ESB framework to support specific protocol.
    ESB accomplish ESB duties such as transformation, translation, routing. Routing use a protocol accepted by the consumer. In a JDBC consumer it is JDBC protocol and hence it a JDBC adaptor.
    There is clear separation on responsibilities among business system and ESB. ESB do not participate in business decision or try to get into business system data layer.
    So who ever are asking people to check duplicate check as part of mapping (an ESB service) may not understand integration practice.
    Please use an adaptor module which will execute the duplicate check with business system in a plug and play approach and separate that from ESB service so that people can build integration using AGILE approach.
    Thanks

  • Connecting to DB2 Database using JDBC for select/Insert

    Hi,
    I am trying to connect to an DB2 Database using  JDBC adapter, I have build an UDF for the same.
    The UDF will try to query the database in the form of Select and INSERT.I am using the LOOKUP API provided by SAP.When I try to execute the UDF I have received the following error.can any of you provide the solution for the error and also is it that the JDBC adapter has to be situated on Central Adapter engine to execute the API, can the JDBC adapter used for executing the INSERT statement.
    Exception during processing the payload.Problem when calling an adapter by using communication channel JDBC_PIDB_Receiver_CC (Party: , Service: XIDB_BSRV, Object ID: 59f2d7694acc3e81840f89b0169d9323) XI AF API call failed. Module exception: (No information available). Cause Exception: (No information available).
    com.sap.aii.mapping.lookup.LookupException: Problem when calling an adapter by using communication channel JDBC_PIDB_Receiver_CC (Party: , Service: XIDB_BSRV, Object ID: 59f2d7694acc3e81840f89b0169d9323) XI AF API call failed. Module exception: (No information available). Cause Exception: (No information available).
         at com.sap.aii.ibrun.server.lookup.AdapterProxyLocal.execute(AdapterProxyLocal.java:131)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorInternal.execute(SystemAccessorInternal.java:68)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorHmiServer.process(SystemAccessorHmiServer.java:149)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorHmiServer.process(SystemAccessorHmiServer.java:77)
         at com.sap.aii.utilxi.hmis.server.HmisServiceImpl.invokeMethod(HmisServiceImpl.java:169)
         at com.sap.aii.utilxi.hmis.server.HmisServer.process(HmisServer.java:178)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.processRequestByHmiServer(HmisServletImpl.java:296)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.processRequestByHmiServer(HmisServletImpl.java:211)
         at com.sap.aii.utilxi.hmis.web.workers.HmisInternalClient.doWork(HmisInternalClient.java:70)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.doWork(HmisServletImpl.java:496)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.doPost(HmisServletImpl.java:634)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:386)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:364)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:1039)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:265)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:102)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:172)
    Root Cause:
    com.sap.aii.af.service.api.AFException: XI AF API call failed. Module exception: (No information available). Cause Exception: (No information available).
         at com.sap.aii.af.service.api.AdapterAccess.sendMsg(AdapterAccess.java:214)
         at com.sap.aii.af.service.api.AdapterAccess.execute(AdapterAccess.java:283)
         at com.sap.aii.ibrun.server.lookup.AdapterProxyLocal.execute(AdapterProxyLocal.java:123)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorInternal.execute(SystemAccessorInternal.java:68)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorHmiServer.process(SystemAccessorHmiServer.java:149)
         at com.sap.aii.ibrun.server.lookup.SystemAccessorHmiServer.process(SystemAccessorHmiServer.java:77)
         at com.sap.aii.utilxi.hmis.server.HmisServiceImpl.invokeMethod(HmisServiceImpl.java:169)
         at com.sap.aii.utilxi.hmis.server.HmisServer.process(HmisServer.java:178)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.processRequestByHmiServer(HmisServletImpl.java:296)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.processRequestByHmiServer(HmisServletImpl.java:211)
         at com.sap.aii.utilxi.hmis.web.workers.HmisInternalClient.doWork(HmisInternalClient.java:70)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.doWork(HmisServletImpl.java:496)
         at com.sap.aii.utilxi.hmis.web.HmisServletImpl.doPost(HmisServletImpl.java:634)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:386)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:364)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:1039)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:265)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:102)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:172)
    Thanks,
    Kiran.

    Hi,
    have you deployed the JDBC driver for your DB2 database in your XI system........if not, then ask your basis guys to find the weblog to deploy the JDBC driver in XI system and then deploy your DB2 database driver in your JDBC driver in XI system............
    then again execute your scenario.
    Regards,
    Rajeev Gupta

  • Retrieving Schema details from any database using JDBC.

    Hi,
    We are in a process of developing a tool to extract the schema level details from any database. Following are the areas where we are facing difficulties. Please give us your valuable comments.
    1.How can I get all the depending views of a particular table or vice- versa ?
    2.If there is a join view in my database.How can i get the information
    for all the join columns?
    3. suppose the view in the database is built using some select and omit
    Clause. how can I get those conditions using JDBC ?
    4.for a viewcolumn , how can I find out, it refers to which column of
    a table ?
    5.For a table how can I get the information about its unique
    constraints and check constraints
    6.How can I check , a constraint is enabled or disabled on any table?
    I will appreciate your response.

    Hi,
    We are in a process of developing a tool to extract
    ct the schema level details from any database.
    Following are the areas where we are facing
    difficulties. Please give us your valuable comments.
    1.How can I get all the depending views of a
    particular table or vice- versa ?No way with JDBC. You need to create something DBMS specific
    2.If there is a join view in my database.How can i get
    the information for all the join columns?see 1)
    3. suppose the view in the database is built using
    some select and omit
    Clause. how can I get those conditions using JDBC
    BC ?see 1)
    4.for a viewcolumn , how can I find out, it refers to
    which column of a table ?see 1)
    5.For a table how can I get the information about its
    unique constraints and check constraintsThe DatabaseMetadata object can return that information
    6.How can I check , a constraint is enabled or
    disabled on any table?I don't think that this is possible with JDBC (not sure
    if that information is returned from the DatabaseMetadata
    object). You will need to code something DBMS specific
    I think there is something with deferred constraints which
    can be checked by JDBC but I'm not sure about that either
    Thomas

  • Inserting a pdf file in mysql database using jdbc

    hi guys,
    i'm developing an application, where i have to upload the documents and store it in the database.
    i'm using mysql db. using the jdbc statements i have stored the contents of the pdf file. But, i'm unable to read the content, it's looks like junk values. and when i retrieved using the stream objects. it looks like the same.
    i'm able to store and retrieve the text based and image files.
    is it possible to store pdf and word documents in the database columns directly??
    any ideas are appreciated.
    thanks in advance,
    -bala

    This may help[
    Table example
    DROP TABLE IF EXISTS `employeephoto`;
    CREATE TABLE `employeephoto` (
    `Employee_ID` varchar(15) NOT NULL default '',
    `Binary_Photo` mediumblob NOT NULL,
    `LastUser` varchar(100) NOT NULL default '',
    `LastMod` datetime NOT NULL default '0000-00-00 00:00:00',
    `Created` datetime NOT NULL default '0000-00-00 00:00:00',
    PRIMARY KEY (`Employee_ID`)
    ) TYPE=MyISAM;
    Save photo as jpeg to database
    public static void saveMySqlPhoto(String empID, ImageIcon icon) {
      try {
        Image image = icon.getImage();
        BufferedImage bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
        Graphics bg = bImage.getGraphics();
        bg.drawImage(image,0,0,null);
        bg.dispose();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bImage,"jpeg",out);
        byte[] buf = out.toByteArray();
        // setup stream for blob
        ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
        // get or create a connection here
        Connection photoConnection = startup.connectionPool.getConnection();
        sqlStatement = "insert into employeephoto (Employee_ID,Binary_Photo,LastUser,LastMod,Created) values ('"+empID+"', ?, '"+startup.User+"', NOW(), NOW())";
        ps = photoConnection.prepareStatement(sqlStatement);
        ps.setBinaryStream(1,inStream,inStream.available());
        ps.executeUpdate();
        // release or close connection here
        startup.connectionPool.releaseConnection(photoConnection);
      catch (Exception exc) {
        // process error
    }Retrieve photo from database
    public static ImageIcon getMySqlPhoto(String employeeID){
      ImageIcon dPhoto = null;
      // get or create a connection here
      Connection photoConnection = connectionPool.getConnection();
      String sqlStatement = "select Binary_Photo from employeephoto where Employee_ID = '"+employeeID+"'";
      try {
        ResultSet rs = photoConnection.createStatement().executeQuery(sqlStatement);
        if (rs.next()){
          Blob image = rs.getBlob("Binary_Photo");
          // setup the streams
          InputStream input = image.getBinaryStream();
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          // set read buffer size
          byte[] rb = new byte[1024];
          int ch = 0;
          // process blob
          while ((ch=input.read(rb)) != -1){
            output.write(rb, 0, ch);
          byte[] b = output.toByteArray();
          input.close();
          output.close();
          // load final buffer
          dPhoto = new ImageIcon(b);
        rs.close();
      catch (Exception exc) {
        // do error processing
      // release or close connection here
      connectionPool.releaseConnection(photoConnection);
      return dPhoto;
    public byte[] toByteArray(int width, int height, BufferedImage imageBuff) throws java.io.IOException{
      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      bi.getGraphics().drawImage(imageBuff, 0, 0, null);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(1.0f, false);
      encoder.setJPEGEncodeParam(param);
      encoder.encode(bi);
      return out.toByteArray();
    }rykk

  • Retieving image from database using webutil

    dear member
    i have 10g db release2, with forms 10g
    i have saved image of the product in a table
    prod_id varchar2(50)
    prodlogo blob(4000)
    how can i retrieve this prodlogo of product on form using webutil or is there any other way of retrieving image.
    thanks.
    teefu.
    lahore,pakistan

    Hi
    You can retrieve the image from the database into a Forms image item, then use client_write_image_file to write this out to the client PC.
    rgds
    Tony

  • Retrieving image from database in form 6i

    hello all
    i'm working on form 6i...
    i have uploded images into the database of customers in my application using READ_IMAGE_FILE.. IT IS FINE...
    But when i am trying retrieves records into the form.... i'm getting all the data except image... Image field is showing empty..
    How can i get image from database to form
    can u plz help me.....
    thanks

    What data type you used for storing image in database. If it is long raw, then you can place an image item within your data block on form and associate it with the column name. This should populate the image by itself.
    Below para is from Forms Help.
    Image items can be populated in the following ways:
    +1. a fetch from a LONG RAW database column+
    An image item in a data block is populated automatically when the end user or the application executes a query in the block.  When a fetched image is modified or replaced, Form Builder marks that record as Changed, and the next commit operation saves the new image to the corresponding LONG RAW column in the database.
    Note:  You cannot write a SELECT statement to select a LONG RAW value INTO an image item.
    +2. executing the READ_IMAGE_FILE built-in to read an image from the file system+
    +(To dynamically write an image from an image item out to a file, use the built-in procedure WRITE_IMAGE_FILE.)+

  • Storing Images in Database using ADF/UIX

    Hello,
    Please let me know of any exmaples or tutorials on how to use Oracle Intermedia to store Images in Database and retrieve the images and display them on UIX.
    I tried using declarative approach of using ADF input form for the table which contains a blob column.
    In the entity object, i changed the blob column type to OrDImageDomain. I changed the Form settings to POST and UsesFileUpload attribute to True.
    I got an error "Incompatible Types" when trying to insert a row in the database table.
    Please provide suggestions/comments
    Thanks a lot.

    Now I'm using OrdFileUploadManager and i'm getting an error message as,
    VB_Pbefore (The system cannot find the file specified. )
    Pbefore is the attribute name of the view object.
    The form that i'm using to insert the row in the database is,
    <labeledFieldLayout>
    <contents>
    <messageChoice model="${bindings.Pid1}">
    <contents childData="${bindings.Pid1.displayData}">
    <option model="${uix.current}"/>
    </contents>
    </messageChoice>
    <messageChoice model="${bindings.Rno1}">
    <contents childData="${bindings.Rno1.displayData}">
    <option model="${uix.current}"/>
    </contents>
    </messageChoice>
    <messageFileUpload model="${bindings.Pbefore}">
    <end>
    <media model="${ctrl:createMediaModel(bindings.Pbefore,'ReoAppModuleLocal')}"/>
    </end>
    </messageFileUpload>
    <messageFileUpload model="${bindings.Pafter}">
    <end>
    <media model="${ctrl:createMediaModel(bindings.Pafter,'ReoAppModuleLocal')}"/>
    </end>
    </messageFileUpload>
    <messageStyledText/>
    <submitButton text="Submit"/>
    <submitButton text="Confirm Repair Photos" model="${bindings.Commit}" id="Commit2" event="action"/>
    </contents>
    </labeledFieldLayout>

  • Creating a new access database using JDBC

    Hi Forum,
    I have a problem in hand. Let me describe the problem:
    I want to create an "access database" from java at runtime. "Access database" is file based, so for a database named test, it will have a file test.mdb.
    Now, everything's sweet and wonderful, if somebody creates an "empty access database" at the client machine and i then connect to it and create the tables i require.
    But the issue is i want to create the database at runtime (the database name and tables are determined at runtime).
    Using the JDBC:ODBC bridge driver , i am able to connect to an existing database, but any "create database" statements are not supported.
    A last ditch solution would be that i create an empty database using access and copy the file contents in the SQL server database as a a blob object. Then when i want to create a new access database at runtime, i create a file in a particular folder , with an .mdb
    extension, copy the file contents from the SQL server (i also have an SQL server connection) BLOB object, and then try to connect to the
    .mdb file.
    But this approach seems a "quick hack" and can have problems (which i can't see as of now).
    Can you suggest a better alternative for the problem.
    See the Java Sun forum at this address for a discussion of a similar problem, but sadly with no solution.
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=484731

    I have an applet that was previously connected to Oracle 9i. I am faced with connecting to MS Access temporarily for testing purposes.
    I have been unable to successfully code connection in java. I have set up the DSN and can access in SQL Worksheet in JDev.
    I saw your question regarding creating an access db, and thought you might be so kind as to help me code the connection to access!!!!
    Any help you could provide would be greatly appreciated. I have a huge application to finish with alot of sqlj already completed. Connectivity is not my area of expertise!
    Any help you could provide would be greatly appreciated!!!
    I am not sure if I have to use bridge? Am I progressing in right direction to migrating to SQL Server if need be?

Maybe you are looking for

  • Two device wifi link file share

    I work away from home and want to know if two iOS devices can connect to each other directly ie: iphone 3gs and ipad 2 I have Simple transfer app which should work great when in a wifi network i have access to at home or friends places What about fli

  • EMPLOYEE AS A CUSTOMER

    How to configure internal employee as a customer in BP master. Thanks Nitin

  • Mail: Reply all includes own email address

    Apple Mail in Yosmite includes my own email address when I reply to all. I can't remember Mavericks or before used to do this. Anyway, is there a way to turn this off?

  • My Airport Express Won't Work

    I need help! I have airport express and it won't work. I have tried the directions step by step, resetting it, going to admin utility and network assistant, but, to no avail. I do have a secure network set up but airport express can't find it. Questi

  • How do you make java components paint to an image?

    I tried having a JPanel as one of my instance variables inside my class. In the paint method i called paint on the JPanel and passed in a graphics2D object created from an image. But JPanel does not paint on my image. How do I make it do that? Basica