mercredi 22 avril 2015

insert blob into sqlitedatabase java

i have created a data base and gui which collects data from user, now i want to add collected data to database. Connection with db is good, however function which is called on button click is failing, reurning me message "null pointer exception: null"

system output:

 Opened database successfully 
 add to  database successfully
 java.lang.NullPointerException: null

addtoBase:

    private void addtoBase(String name, int row, BufferedImage img) throws Exception, IOException, SQLException {
    PreparedStatement st = null;
    FileInputStream fis = null; 
    Connection con = null;

    try {
    Class.forName("org.sqlite.JDBC").newInstance();
    con = DriverManager.getConnection("jdbc:sqlite:heores.sqlite");
    con.setAutoCommit(false);
    System.out.println("Opened database successfully");
    FileInputStream inputStream= new FileInputStream(selectedFile.getAbsolutePath());
    String sql = "INSERT INTO hero (name, row, img) values (?, ?, ?)";
    st = con.prepareStatement(sql);

    st.setString(1, name);
    st.setInt(2, row);
    st.setBlob(3,inputStream);
    st.executeUpdate();
    con.commit();
    System.out.println("add to  database successfully");
    }

    catch(Exception e) {
    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
    System.exit(0);
    }


    finally {
    st.close();
    fis.close();
    }

}

button action listener:

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String name;
    int row;
    BufferedImage img;

    switch(Row.getSelectedItem().toString()){
        case "Front":{
            row =1;
        }
        case "Middle":{
            row =2;
        }
        case "Back":{
            row =3;
        }
        default:{
            row=0;
        }

    }
    name=name1.getText();
    img = toBufferedImage(image);

    try {
        addtoBase(name, row, img);

    } catch ( Exception e ) {
    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
    System.exit(0);
    }
}

Any ideas whats wrong? after opening database it seems like all colums are filled except for img collumn (Blob), file that im insetring is decleared in main:

public class Main extends javax.swing.JFrame {

Image image;
File selectedFile = new File("avatar.png");
//...

Aucun commentaire:

Enregistrer un commentaire