Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2006

Tip: Looking for answers? Try searching our database.

Question about blob retrieving and jsp...

Thread view: 
gbattine - 28 Jun 2006 09:28 GMT
Hi guys,
i've a question and i don't find solution in google and forums...
i have a blob in a mysql db column(named Data),i want to retrieve it as
an array of byte....i understand i have to do

ResultSet rs = conn.createStatement().executeQuery("SELECT Nome,Data
FROM tbl");
while (rs.next()) {
    Blob blob = rs.getBlob("Data");
                    byte[] read=????????

now i want to obtain an array of byte, i see the getBytes from Blob but
how can i specifing dimension of array byte?
Can you help me?
Later i've developed this function that reads the array of byte read
and rebuild the original format of the file

String lettura=new String(read);
           //System.out.println("La stringa di lettura e'  "+lettura);
           System.out.println("Le stringhe splittate sono");
           String[] arraylinee=lettura.split(";");
           for (int i = 0; i < arraylinee.length; i++) {
               String elemento = arraylinee[i];
               try {
                 double mioDouble = Double.parseDouble(elemento);

               }
               catch (NumberFormatException e) {
                 System.out.println(elemento);
               }
           }

My questions are:
1) how can i obtain the array of byte from blob object?(please help me
with code)
2) Do you know how can i show directly string[] arraylinee(that is the
result) in a jsp page?

Thanks very much......
Jean-Francois Briere - 28 Jun 2006 10:06 GMT
1)
Blob blob = rs.getBlob("Data");
byte[] read = blob.getBytes(0, blob.length());

2)
<%
for (int i = 0; i < arraylinee.length; i++) {
   out.print(arraylinee[i]);
   out.println("<br>");
}
%>

Regards
Moiristo - 28 Jun 2006 11:17 GMT
> 1)
> Blob blob = rs.getBlob("Data");
> byte[] read = blob.getBytes(0, blob.length());

should be 'blob.getBytes(1, blob.length());' ;) i used it yesterday...
dsjoblom@abo.fi - 28 Jun 2006 14:52 GMT
> > 1)
> > Blob blob = rs.getBlob("Data");
> > byte[] read = blob.getBytes(0, blob.length());
>
> should be 'blob.getBytes(1, blob.length());' ;) i used it yesterday...

It should be blob.getBytes(1, (int) blob.length()); even. You see, I
used it today ;-)

Regards,
Daniel Sjöblom
Jeffrey Schwab - 28 Jun 2006 14:56 GMT
>>> 1)
>>> Blob blob = rs.getBlob("Data");
[quoted text clipped - 3 lines]
> It should be blob.getBytes(1, (int) blob.length()); even. You see, I
> used it today ;-)

One has to wonder...  Why does blob.length() return type long, while
getBytes() expects type int?
dsjoblom@abo.fi - 28 Jun 2006 15:07 GMT
> >>> 1)
> >>> Blob blob = rs.getBlob("Data");
[quoted text clipped - 6 lines]
> One has to wonder...  Why does blob.length() return type long, while
> getBytes() expects type int?

Because arrays in Java have 32-bit length, but a LONGBLOB in a database
can be larger. Same thing happens with files. I do think that Java will
eventually have to undergo some major changes as 64-bit architectures
are becoming more common.

Regards,
Daniel Sjöblom
Jeffrey Schwab - 28 Jun 2006 15:08 GMT
>>>>> 1)
>>>>> Blob blob = rs.getBlob("Data");
[quoted text clipped - 9 lines]
> eventually have to undergo some major changes as 64-bit architectures
> are becoming more common.

Thank you for the satisfying answer.
Moiristo - 28 Jun 2006 15:37 GMT
>>> 1)
>>> Blob blob = rs.getBlob("Data");
[quoted text clipped - 3 lines]
> It should be blob.getBytes(1, (int) blob.length()); even. You see, I
> used it today ;-)

you're right :) I had a rough night yesterday ;)
gbattine - 28 Jun 2006 16:48 GMT
Thanks very much guys..........
i don't understand what is happening to my jsf application.
It runs perfectly but don't insert the array of byte in the blob field
of mysql db...
can you help me finding the problem?
Thanks

my java application works fine,but i don't understand while,going in my
jsf application the application runs but don't insert value into table
of my db....can someone help me?
This is the bean i invoke when i clic upload button
package giu;

import org.apache.myfaces.custom.fileupload.UploadedFile;

import giu.Head;
import giu.Riga;
import java.sql.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;

import java.io.*;

public class MyBean {
    private UploadedFile myFile;

    private String geneid = null;

    private static int row = 0;

    private static int numberOfNumericColumns = 0;

    private static int col = 0;

    String[] intest = null;

    private ArrayList rows = new ArrayList();

    Head h;

    Riga r;

    byte middlerow = ' ';

    byte endrow = ';';

    byte[] data = null;

    Vector temp = new Vector(100000);

    String g = null;

    Riga r;

    Double val[];

    public boolean insRighe(Riga nuovo) {
        return rows.add(nuovo);
    }

    public List stampaRows() {
        return rows;
    }

    public Head stampaHead() {
        return h;
    }

    public boolean insRighe(Riga nuovo) {
        return rows.add(nuovo);
    }

    public List stampaRows() {
        return rows;
    }

    public Head stampaHead() {
        return h;
    }

    public byte[] getdata() {
        return data;
    }

    public String carica() throws IOException {
        System.out.println("eccomi0");
        FileReader reader = new FileReader(fileName);
        System.out.println("eccomi99");
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        System.out.println("eccomi1");
        while ((line = br.readLine()) != null) {
            line = line.replace(',', '.');
            StringTokenizer st = new StringTokenizer(line);
            numberOfNumericColumns = (st.countTokens() - 1);
            col = (numberOfNumericColumns + 1);
            //se siamo nella prima riga(contatore segna 0)
            if (row == 0) {
                intest = new String[col];
                int j = 0;
                while (st.hasMoreTokens()) {
                    intest[j] = (st.nextToken().trim());
                    j++;
                }
                h = new Head(intest);//crei l'oggetto head
                String[] qa = h.getHvalues();
                String asd = "";
                for (int i = 0; i <= qa.length - 1; i++) {
                    asd = asd.concat(qa[i] + " ");
                }
                System.out.println("head " + asd);//stampo contenuto dell' head
                row = 1;
            }//fine if

            else {
                Double[] values = new Double[numberOfNumericColumns];
                int z = 0;
                geneid = st.nextToken();
                while (st.hasMoreTokens()) {
                    String app = st.nextToken();
                    values[z] = Double.valueOf(app);
                    z++;
                }
                r = new Riga(geneid, values); //crei l'oggetto riga
                System.out.println("riga");
                System.out.println(r.getgeneid());
                values = r.getvalues();
                for (int e = 0; e <= values.length - 1; e++) {
                    System.out.println(values[e]);
                }
                insRighe(r); //aggiungi
            }
            row++;
        }
        while (i < intest.length) {

            byte[] bytesnew = intest[i].getBytes();
            //temp.addAll(bytesnew);
            //memorizza in byte un elemento del vettore alla volta

            for (byte b : bytesnew)
                temp.add(new Byte(b)); //provare Byte
            //temp.addElement(intest[i].getBytes());
            temp.addElement(Byte.valueOf(middlerow));
            i++;
        }
        temp.addElement(Byte.valueOf(endrow));
        System.out.println("Intestazione convertita in byte");

        for (int l = 0; l < rows.size(); l++) {
            r = (Riga) rows.get(l);
            g = r.getgeneid();
            //temp.addElement(g.getBytes());

            byte[] byte2 = g.getBytes();
            for (byte c : byte2)
                temp.add(new Byte(c));

            temp.addElement(Byte.valueOf(middlerow));
            val = r.getvalues();

            byte[] tempByte1;
            for (int e = 0; e <= val.length - 1; e++) {
                //Returns a string representation of the double argument.
                tempByte1 = Double.toString(val[e]).getBytes();

                for (int j = 0; j < tempByte1.length; j++) {
                    temp.addElement(Byte.valueOf(tempByte1[j]));

                }
                temp.addElement(Byte.valueOf(middlerow));
            }
            temp.addElement(Byte.valueOf(endrow));
        }
        data = new byte[temp.size()];
        //OutputStream os=new OutputStream(file);
        for (int t = 0; t < temp.size() ; t++) {
            data[t] = (((Byte) temp.elementAt(t)).byteValue());

        }
        Test t=new Test();
        t.addtoblob(data);

        return "success";

    }

}

and before terminating this bean call the method addtoblob of class
Test...

import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;
import java.sql.*;

public class Test {
    public void addtoblob(byte[] datanew) {
        Database dbs = new Database("nomeDB", "root", "shevagol");
        if (!dbs.connetti()) {
            System.out.println("Errore durante la connessione.");
            System.out.println(dbs.getErrore());
            System.exit(0);
        }
        try {
            Connection db = dbs.getConnection();
            PreparedStatement pst = db
                    .prepareStatement("INSERT INTO tbl(Nome,Data) VALUES (?,?)");
            //imposto i valori
            pst.setString(1, "ciao21");
            pst.setBytes(2, datanew);
            pst.executeUpdate();
            pst.close();
        } catch (SQLException sqlex) {
            sqlex.printStackTrace();
        }
        // Stampiamo i risultati:
        dbs.disconnetti();
    }

Is here the error?
My application don't gives me error,but don't insert nothing in the
table,while my same java application do it well...can someone help me?
Thanks
Moiristo - 29 Jun 2006 18:18 GMT
>             pst.setBytes(2, datanew);

Have you changed this already?
Does the bytearray 'data' in your bean contain any data (test it by
adding 'System.out.println(new String(data));' or something to your bean..


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.