Why this application doesn't work correctly?

Why connecting an application with a mysql db is so difficult?

Please help me,it's important and i'm crazing....

I'm developing a jsf application and i have this function

public String carica()throws IOException{

BufferedReader br =new BufferedReader(new InputStreamReader(myFile.getInputStream()));

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

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=newbyte[temp.size()];

//OutputStream os=new OutputStream(file);

for (int t=0;t<temp.size()-1;t++){

data[t]=(((Byte)temp.elementAt(t)).byteValue());

}

dbs.addtoblob(data);

return"success";

}

where myFile is the file i upload.

Later my application receive the file,stores it into an array of byte(data in the application) and i have only to put it with string ciao in a table of a mysql db composed by two columns, one string, one blob.

The td is named nomeDB and the table is named Tbl.

It's so difficult?

I've developed two classes:

Database.java that care connection with database

import java.sql.*;

import java.util.Vector;

publicclass 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

privateboolean 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

publicboolean 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;

}

// Chiude la connessione con il Database

publicvoid disconnetti(){

try{

db.close();

connesso =false;

}catch (Exception e){ e.printStackTrace();}

}

publicboolean 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;}

e

uploadData.java that execute query

import java.io.IOException;

import java.io.StringReader;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.util.Vector;

publicclass uploadData{

private database dbs=new database("nomedb","root","shevagol");

privatebyte[] data=MyBean.getdata();

public uploadData(){

}

publicvoid addtoblob(data){

if ( !dbs.connetti() ){

System.out.println("Errore durante la connessione.");

System.out.println( dbs.getErrore() );

System.exit(0);

}

Connection db=dbs.getConnection();

PreparedStatement pst = db.prepareStatement("INSERT INTO Tbl(Nome,File) VALUES (?, ?)");

// imposto i valori

String value =new String(data);

pst.setString(1,"ciao");

pst.setCharacterStream(2,new StringReader(value), data.length);

pst.executeUpdate();

pst.close();

}

}

Why my string "ciao" and the file i put with the array of byte don't go in my db table?

In my function carica i have inserted the instruction :

codice:dbs.addtoblob(data);

so when i run carica why my application doesn't give me the expected results?

Thanks very much

Vi prego aiutatemi.....sto impazzendo con questo problema>

[14473 byte] By [giubata] at [2007-10-2 23:23:16]
# 1

This doesn't even compile. You have a Database class, but you try to instantiate a database class (Note the case difference)....

public class Database

and

private database dbs=new database("nomedb","root","shevagol");

SurfManNLa at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 2

thanks very much.....i have modified my code but i have an exception...can you help me?

I'm inexpert of java and object oriented programming, can you help me reading my code and giving me some helps?

Can you help me to solve my exception?

I poste my new code and at the end the exception.....thanks very much

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[i] = 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; }

}

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=null;

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;

byte middlerow=' ';

byte endrow=';';

byte[] data=null;

Vector temp=new Vector(100000);

int i=0;

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 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

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()];

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,File) VALUES (?, ?)");

//imposto i valori

String value = new String(datanew);

pst.setString(1, "ciao");

pst.setCharacterStream(2, new StringReader(value), datanew.length);

pst.executeUpdate();

pst.close();

}

catch(SQLException e){};

// Stampiamo i risultati:

dbs.disconnetti();

}

public static void main(String[] args)throws IOException {

princ p=new princ();

try{

p.carica();

}

catch(IOException e){};

byte[] datanew=p.getdata();

Test t=new Test();

t.addtoblob(datanew);

}

}

And this is my exception

Exception in thread "main" java.lang.NullPointerException

at java.lang.String.><init>(Unknown Source)

at Test.addtoblob(Test.java:27)

at Test.main(Test.java:53)

giubata at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 3

The exception tells you the line number at which it occurs. It's a NullPointerException - something wasn't initialized correctly.

Exception in thread "main" java.lang.NullPointerException

at java.lang.String.><init>(Unknown Source)

at Test.addtoblob(Test.java:27)

at Test.main(Test.java:53)

Turn on line numbers in your text editor, go to line 27 in Test.java, and look at all the objects being dereferenced. One of them is null. Figure out why.

%

duffymoa at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 4

Your carınca method is too messy that's why I do not trace it but there is something in that method that cause NullPointerException to be thrown.

This means that you use a reference variable which points to the null value instead of any object. So you can tracwe and find the error.

samue-1a at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 5
But how can is it possible?The method carica worked fine before i've inserted Database e uploadData method..........mah.....can you help me finding the problem?I've seen the entire code but nothing is wrong initialited!!!
giubata at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 6
Are you sure that this does not throw exception ?h=new Head(intest);//crei l'oggetto head String []qa=h.getHvalues();
samue-1a at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...
# 7
i think no......what have i do?
giubata at 2007-7-14 16:01:40 > top of Java-index,Java Essentials,Java Programming...