Translate

viernes, 26 de septiembre de 2014

Trabajar con imagenes en Base de Datos con JAVA

Imaginemos que tenemos una base de datos que contiene una tabla llamada IMAGENES, que tiene una columna tipo BLOB (denominada FOTO) y un identificador (denominado ID). Para consultar desde la base datos la foto podemos hacer la siguiente consulta:
ResultSet rs = stmt.executeQuery(”SELECT FOTO FROM IMAGENES WHERE ID = 1″);
rs.next(); //Esto hacía falta
byte[] img = rs.getBytes(”FOTO”);

Para sacar una imagen de una BD.

PreparedStatement pstmt = null;
ResultSet rs = null;
ImageIcon ii = null;
int valor = 1;
lSql="SELECT imagen FROM imagenes WHERE ( codigo_imagen = ?)";
pstmt = sqlca.getConnection().prepareStatement(lSql);
pstmt.setInt(1,valor);
rs = pstmt.executeQuery();

try{
    if(rs.next()){
    byte[] a = rs.getBytes(1);
    ii = new ImageIcon(a);
}

jLabel1.setIcon(ii);

}catch(Exception es){
    System.out.println("Error. "+es);
}


Extraer una imagen de la bd

Conexion con = new Conexion();
Connection c = null;
PreparedStatement stm = null;
ResultSet rs = null;
String sql = "select imagen from imagenes where clave = ?";
ImageIcon imagen = null;
try {
    c = con.getConnection();
    stm = c.prepareStatement(sql);
    stm.setInt(1, 1);
    rs = stm.executeQuery();

    if(rs != null){
       while(rs.next()){
          byte[] bytes = rs.getBytes("imagen");
          imagen = new ImageIcon(bytes);
      }
     jLabel1.setIcon(imagen);
    }
} catch (SQLException f) {
    System.out.println("error");
}

Meter una imagen a la base de datos

PreparedStatement stm = null;
String sql = "insert into imagenes values(?,?,?,?,?)";
File foto = new File("F:\\imagenes\\workorder.gif");
FileInputStream fis;
 
try {
    Conexion con = new Conexion();
    Connection c = con.getConnection();
    stm = c.prepareStatement(sql);

    fis = new FileInputStream(foto);
    stm.setInt(1, 1);
    stm.setString(2, foto.getName());
    stm.setString(3, foto.getParent());
    stm.setInt(4, (int)foto.length());
    stm.setBinaryStream(5, fis, (int)foto.length());
    stm.executeUpdate();
    fis.close();
    stm.close();
    c.close();
} catch (FileNotFoundException e) {
    System.out.println("error...de e-s");
} catch (SQLException e) {
    System.out.println("error...de sql");
} catch (IOException e) {
    System.out.println("error...de io");
}


No hay comentarios.:

Publicar un comentario