where is the error....???help me to find it!!!!

G

gbattine

Hi guys,
i'm a great problem. I've developed a java application that receive in
input a txt file, stores it into an array of byte and put it in a blob
field of a mysql db in the table tbl that has 2 columns, a string and a
blob.
The question is that i have a function called carica that create the
array of bytes and another function Test.java that put the array of
byte into the blob field and a string in the string field.
The problem is that the string is inserted correctly while the blob
no,it's null.
There is(i think) a problem in the passing array of bytes (called
data)beetwen carica function and test.
Can you help me,please?
I'm crazing and i'm stopping....please help me to go on

princ.java
import java.io.BufferedReader;
import java.io.*;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.*;
import java.sql.*;

import java.util.*;
public class princ {
private static String fileName = "dato2.txt";
//private static String file = "ris.txt";
private String geneid;
private static int row=0;
private static int numberOfNumericColumns=0;
private static int col=0;
Double[] values=new Double[numberOfNumericColumns];
String[]intest=null;
private ArrayList rows = new ArrayList();
Head h=null;
byte middlerow=' ';
byte endrow=';';
byte[] data;
Vector temp=new Vector(100000);
int i=0;
Riga r;
String g=null;
Double val[]=null;
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 byte[] carica()throws IOException{
FileReader reader=new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
String line = null;
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




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.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.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();
System.out.println("la carica va benw");
}


byte[] tempByte1=null;
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()];

for (int t=0;t<temp.size()-1;t++)
data[t]=(((Byte)temp.elementAt(t)).byteValue());

return data;

}



}




Test.java
import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;
import java.sql.*;
import javax.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, "ciao3");
pst.setBytes(2, datanew);

pst.executeUpdate();

pst.close();
}
catch(SQLException sqlex) {
sqlex.printStackTrace();
}



// Stampiamo i risultati:

dbs.disconnetti();
}

public static void main(String[] args)throws IOException {
princ p=new princ();
try{
p.carica();
System.out.println("eccezione buona");
}
catch(IOException e){System.out.println("eccezione negativa");
};
System.out.println("ciao");
byte[] datanew=p.getdata();
Test t=new Test();
t.addtoblob(p.getdata());


}
}


Database.java
import java.sql.*;
import java.util.Vector;

public class Database {
private String nomeDB; // Nome del Database a cui connettersi
private String nomeUtente; // Nome utente utilizzato per la
connessione al Database
private String pwdUtente; // Password usata per la connessione al
Database
private String errore; // Raccoglie informazioni riguardo
l'ultima eccezione sollevata
private Connection db; // La connessione col Database
private boolean connesso; // Flag che indica se la connessione è
attiva o meno

public Database(String nomeDB) { this(nomeDB, "", ""); }

public Database(String nomeDB, String nomeUtente, String pwdUtente)
{
this.nomeDB = nomeDB;
this.nomeUtente = nomeUtente;
this.pwdUtente = pwdUtente;
connesso = false;
errore = "";
}

// Apre la connessione con il Database
public boolean connetti() {
connesso = false;
try {

// Carico il driver JDBC per la connessione con il database
MySQL
Class.forName("com.mysql.jdbc.Driver");

// Controllo che il nome del Database non sia nulla
if (!nomeDB.equals("")) {

// Controllo se il nome utente va usato o meno per la
connessione
if (nomeUtente.equals("")) {

// La connessione non richiede nome utente e password
db =
DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
} else {

// La connessione richiede nome utente, controllo se
necessita anche della password
if (pwdUtente.equals("")) {

// La connessione non necessita di password
db =
DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB +
"?user=" + nomeUtente);
} else {

// La connessione necessita della password
db =
DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB +
"?user=" + nomeUtente + "&password=" + pwdUtente);
}
}

// La connessione è avvenuta con successo
connesso = true;
} else {
System.out.println("Manca il nome del database!!");
System.out.println("Scrivere il nome del database da
utilizzare all'interno del file \"config.xml\"");
System.exit(0);
}
} catch (Exception e) { errore = e.getMessage(); }
return connesso;
}
public boolean eseguiAggiornamento(String query) {
int numero = 0;
boolean risultato = false;
try {
Statement stmt = db.createStatement();
numero = stmt.executeUpdate(query);
risultato = true;
stmt.close();
} catch (Exception e) {
e.printStackTrace();
errore = e.getMessage();
risultato = false;
}
return risultato;
}
public Vector eseguiQuery(String query) {
Vector v = null;
String [] record;
int colonne = 0;
try {
Statement stmt = db.createStatement(); // Creo lo
Statement per l'esecuzione della query
ResultSet rs = stmt.executeQuery(query); // Ottengo il
ResultSet dell'esecuzione della query
v = new Vector();
ResultSetMetaData rsmd = rs.getMetaData();
colonne = rsmd.getColumnCount();

while(rs.next()) { // Creo il vettore risultato scorrendo
tutto il ResultSet
record = new String[colonne];
for (int i=0; i<colonne; i++) record =
rs.getString(i+1);
v.add( (String[]) record.clone() );
}

rs.close(); // Chiudo il ResultSet
stmt.close(); // Chiudo lo Statement
} catch (Exception e) { e.printStackTrace(); errore =
e.getMessage(); }

return v;
}


// Chiude la connessione con il Database
public void disconnetti() {
try {
db.close();
connesso = false;
} catch (Exception e) { e.printStackTrace(); }
}

public boolean isConnesso() { return connesso; } // Ritorna TRUE
se la connessione con il Database è attiva
public String getErrore() { return errore; } // Ritorna il
messaggio d'errore dell'ultima eccezione sollevata
public Connection getConnection() { return db; }

}

Please help me!!!!!
 
M

Moiristo

gbattine said:
Hi guys,
i'm a great problem. I've developed a java application that receive in
input a txt file, stores it into an array of byte and put it in a blob
field of a mysql db in the table tbl that has 2 columns, a string and a
blob.
The question is that i have a function called carica that create the
array of bytes and another function Test.java that put the array of
byte into the blob field and a string in the string field.
The problem is that the string is inserted correctly while the blob
no,it's null.
There is(i think) a problem in the passing array of bytes (called
data)beetwen carica function and test.
Can you help me,please?
I'm crazing and i'm stopping....please help me to go on

I think that you shouldn't use getBytes() (however I have no proof it is
incorrect). The method I always use is pst.setBinaryStream:

-> pst.setBinaryStream(new ByteArrayInputStream(datanew));


Hope this helps...
 
T

Timo Stamm

gbattine said:
Hi guys,
i'm a great problem. I've developed a java application that receive in
input a txt file, stores it into an array of byte and put it in a blob
field of a mysql db

This is a bad idea because you loose encoding information (your are
probably using an implicit default encoding and create nasty bugs) and
because the database can neither store the data in an optimal way nor
provide type-specific features like search, sort, indexes, text
manipulation functions.

Use the SQL type "TEXT" for text.

in the table tbl that has 2 columns, a string and a
blob.
The question is that i have a function called carica that create the
array of bytes and another function Test.java that put the array of
byte into the blob field and a string in the string field.
The problem is that the string is inserted correctly while the blob
no,it's null.

The documentation for PreparedStatement#setBytes says:

| Sets the designated parameter to the given Java array of bytes. The
| driver converts this to an SQL VARBINARY or LONGVARBINARY (depending
| on the argument's size relative to the driver's limits on VARBINARY
| values) when it sends it to the database.

You don't have a VARBINARY or LONGVARBINARY type in the database, but a
BLOB.

You can either create a Blob object and set the bytes on it or use
PreparedStatement#setBinaryStream. I think you could reduce the entire
method "princ" to a single line of code.


Timo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top