Gravar e Recuperar imagens do banco MySql

3 respostas
habinovich

Galera to com um problema aki pra fazer na minha tela de cadastro o carregamento da imagem...

Tenho seguindo esquema

tenho minha tela com o botao e um label q fiz para receber a imagem..

no botão tenho o seguindo evento:
private void InserirButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
       //Criação do FileChooser
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Importar imagem");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        //Abre a caixa para escolher a imagem
        if (fileChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
            return ;
        }
         inserirIm.setIcon(new ImageIcon(fileChooser.getSelectedFile().getPath()));
    }
Tenha o seguinte metodo que o chamo na meu botao salva:
private void InserirImagem(){
        conCheck.conecta();
        conCheck.execute("INSERT INTO `siscomjava`.`itens` (imagens) VALUES ("+inserirIm+")");
 }
O meu Conexão eh esse!
package br.com.siscom.utilitarios;

import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Conexao {

    final private String driver = "com.mysql.jdbc.Driver";
    final private String url = "jdbc:mysql://localhost:3306/siscomjava";
    final private String usuario = "root";
    final private String senha = "1234";
    public Connection conexao;
    public Statement statement;
    public ResultSet resultset;
    public PreparedStatement psrt;

    public boolean conecta() {
        boolean result = true;
        try {
            Class.forName(driver);
            conexao = DriverManager.getConnection(url, usuario, senha);
            System.out.println("CONECTOU");
        } catch (ClassNotFoundException Driver) {
            System.out.println("DRIVER NÃO LOCALIZADO " + Driver);
            result = false;
        } catch (SQLException Fonte) {
            System.out.println("DEU ERRO NA CONEXÃO " + "COM A FONTE DE DADOS" + Fonte);
            result = false;
        }
        return result;
    }

    public void desconecta() {
        boolean result = true;
        try {
            conexao.close();
            System.out.println("Conexão com banco FECHADA");
        } catch (SQLException fecha) {
            System.out.println("NÃO FOI POSSIVEL " + "FECHAR O BANCO DE DADOS " + fecha);
            result = false;
        }
    }

    public void executeSQL(String sql) {
        boolean result = true;
        try {
            statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            resultset = statement.executeQuery(sql);
        } catch (SQLException sqlex) {
            System.out.println("executeSQL: NÃO FOI POSSIVEL " + "EXECUTAR O COMANDO sql " + sqlex + " , o sql passado foi: \n" + sql);
            result = false;
        }

    }

    public void executeUpdate(String sqlupdate) {
        try {
            statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.executeUpdate(sqlupdate);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
}
}
Acaba me retornando o seguinte erro:
executeSQL: NÃO FOI POSSIVEL EXECUTAR O COMANDO sql java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). , o sql passado foi: 
INSERT INTO `siscomjava`.`itens` (imagens) VALUES (javax.swing.JLabel[,20,32,163x200,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@14c4066,
flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=D:\3D\1751_128x128.png,disabledIcon=,horizontalAlignment=LEADING,
horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,verticalTextPosition=CENTER])

Espero ter explicado de uma forma que dê para entender o que estou fazendo ou tentando fazer :lol:

Desde ja galera agradeço pela ajuda...

3 Respostas

L

aqui para gravar imagem no banco

public  void inserir(Cliente cli, File file) throws FileNotFoundException, IOException {   
        
FileInputStream fis = new FileInputStream(file);   
               
        String sql = "INSERT INTO cliente (nome_cliente, cpf_cliente, estado_cliente, data_cliente, foto_cliente) VALUES (?,?,?,?,?)";   
        try {   
            PreparedStatement stmt = getConexao().prepareStatement(sql);   
             
            stmt.setString(1, cli.getnome_cliente());   
            stmt.setString(2, cli.getcpf_cliente());   
            stmt.setString(3, cli.getestado_cliente());   
            stmt.setDate(4, new java.sql.Date(cli.getdata_cliente().getTime()));   
               
             stmt.setBinaryStream(5, fis, (int)file.length());   //aqui grava imagem como bytea   
               
            stmt.executeUpdate();   
            stmt.close();      
       fis.close();     
               
        } catch (SQLException sQLException) {   
            System.out.println("Erro ao inserir Cliente." + sQLException.getMessage());   
        }   
           
    }  
 public  void inserir(Cliente cli, File file) throws FileNotFoundException, IOException {
     
FileInputStream fis = new FileInputStream(file);
            
        String sql = "INSERT INTO cliente (nome_cliente, cpf_cliente, estado_cliente, data_cliente, foto_cliente) VALUES (?,?,?,?,?)";
        try {
            PreparedStatement stmt = getConexao().prepareStatement(sql);
          
            stmt.setString(1, cli.getnome_cliente());
            stmt.setString(2, cli.getcpf_cliente());
            stmt.setString(3, cli.getestado_cliente());
            stmt.setDate(4, new java.sql.Date(cli.getdata_cliente().getTime()));
            
             stmt.setBinaryStream(5, fis, (int)file.length());   //aqui grava imagem como bytea
            
            stmt.executeUpdate();
            stmt.close();   
       fis.close();  
            
        } catch (SQLException sQLException) {
            System.out.println("Erro ao inserir Cliente." + sQLException.getMessage());
        }
        
    }

e para recupera a imagemfiz 2 metodos

1 pega o array de bytes do banco e cria um arquivo com a imagem correspodente

public Image getImagens(Cliente cli) throws SQLException, FileNotFoundException, IOException {      
  
          String sql = "SELECT foto_cliente FROM Cliente WHERE id_cliente = ?";   
  PreparedStatement stmt = getConexao().prepareStatement(sql);    
    
     
 stmt.setInt(1, cli.getid_cliente());    
ResultSet rs = stmt.executeQuery();      
     
    
          if (rs.next()){      
             byte[] imgBytes = rs.getBytes(1);      
                OutputStream out = new FileOutputStream("arquivo.jpg");      
                      
                out.write(imgBytes);      
                out.close();      
                System.out.println(out);                  
         
      System.out.println("Tamanho da imagem: " + imgBytes.length);            
   }              
File sourceimage = new File("arquivo.jpg");   
     imagem = ImageIO.read(sourceimage);   
cli.setFoto_Cliente(imagem);   
      
   rs.close();         
          
stmt.close();      
  return imagem;   
     
 }    
 public Image getImagens(Cliente cli) throws SQLException, FileNotFoundException, IOException {   

          String sql = "SELECT foto_cliente FROM Cliente WHERE id_cliente = ?";
  PreparedStatement stmt = getConexao().prepareStatement(sql); 
 
  
 stmt.setInt(1, cli.getid_cliente()); 
ResultSet rs = stmt.executeQuery();   
  
 
          if (rs.next()){   
             byte[] imgBytes = rs.getBytes(1);   
                OutputStream out = new FileOutputStream("arquivo.jpg");   
                   
                out.write(imgBytes);   
                out.close();   
                System.out.println(out);               
      
      System.out.println("Tamanho da imagem: " + imgBytes.length);         
   }           
File sourceimage = new File("arquivo.jpg");
     imagem = ImageIO.read(sourceimage);
cli.setFoto_Cliente(imagem);
   
   rs.close();      
       
stmt.close();   
  return imagem;
  
 }

2 pega somente a imagem sem criar arquivo nehum presisa cria uma variavel do tipo IMAGE

EX usar imagem como icone de um jbutton
jButton2.setIcon(new ImageIcon(clienteD.getImagens((2))));

ImageIcon foto= getImagens(1)
foto tem a imagem

  public ImageIcon getImagen(Integer id) throws SQLException {        
     
          String sql = "SELECT foto_cliente FROM Cliente WHERE id_cliente = ?";      
  PreparedStatement stmt = getConexao().prepareStatement(sql);      
        
stmt.setInt(1, id);      
ResultSet rs = stmt.executeQuery();        
ImageIcon photo = null;      
                    
          if (rs.next()){        
             photo = new ImageIcon(rs.getBytes(1));      
   }      
   rs.close();            
            
stmt.close();      
  
  return photo;      
        
}

e tbm pq vc POSTOU sua duvida em [color=red][size=18]Assuntos gerais ?????(Off-topic) [/size][/color]

habinovich

Postei la pq n sabia a area certa para postar…

Vou tentar usar o seu exemplo pode me passa sua conexao?

att,

habinovich

Alguem tem mas alguma dica???

att,

Criado 27 de agosto de 2010
Ultima resposta 30 de ago. de 2010
Respostas 3
Participantes 2