package sqlimage;
import java.awt.*;
import java.sql.*;
import java.io.*;
import javax.swing.*;
/**
 *
 * @author  Roland Naake
 */
public class SqlImage extends javax.swing.JDialog {
    private Connection connection = null;
    
    /** Creates new form SqlImage */
    public SqlImage(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sqlImage","root","geheim");
        } catch (Exception ex) {
            System.out.println(ex.toString());
            System.exit(1);
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLName = new javax.swing.JLabel();
        jTFName = new javax.swing.JTextField();
        jBEinfuegen = new javax.swing.JButton();
        jBSuchen = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextausgabe = new javax.swing.JTextPane();
        jLBild = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jLName.setText("Name");
        jBEinfuegen.setText("einfÃŒgen");
        jBEinfuegen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBEinfuegenActionPerformed(evt);
            }
        });
        jBSuchen.setText("suchen");
        jBSuchen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSuchenActionPerformed(evt);
            }
        });
        jScrollPane1.setViewportView(jTextausgabe);
        jLBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLBild.setText("<html>Kein [b]Bild[/b]
verfÃŒgbar!</html>");
        jLBild.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(15, 15, 15)
                                .add(jLName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 43, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 42, Short.MAX_VALUE)
                                .add(jTFName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 130, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(jLBild, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 101, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(50, 50, 50)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jBSuchen, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
                                    .add(jBEinfuegen, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE))))
                        .add(171, 171, 171))
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTFName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLName))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jBEinfuegen)
                        .add(18, 18, 18)
                        .add(jBSuchen))
                    .add(jLBild, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 208, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
private void jBEinfuegenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEinfuegenActionPerformed
// TODO add your handling code here:
    if (jTFName.getText().length() > 0) {
        JFileChooser ch = new JFileChooser();
        ch.setMultiSelectionEnabled(false);
        int r = ch.showOpenDialog(this);
        
        if (r == JFileChooser.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(this, 
                "Auswahl abgebrochen!\n");
            return;
        }
        
        if (r == JFileChooser.APPROVE_OPTION) {
            
            File f = null;
            FileInputStream fis = null;
            PreparedStatement ps = null;
            String query = "INSERT INTO sqlImage (name,bild) VALUE ( ?, ? )";
            
            try {
                f = ch.getSelectedFile();
                fis = new FileInputStream(f);
                
                ps = connection.prepareStatement(query);
                ps.setString(1, jTFName.getText());
                ps.setBinaryStream(2, fis, (int)f.length());
                ps.executeUpdate();
                
                JOptionPane.showMessageDialog(this, 
                    "Datensatz eingefÃŒgt!\n");
                fis = new FileInputStream(f);
                Image obild = javax.imageio.ImageIO.read(fis);
                Image htmlBild = obild.getScaledInstance(75,100, Image.SCALE_SMOOTH);
                jLBild.setIcon(new ImageIcon(htmlBild));
                jLBild.setText("");
                
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.toString());
            } finally {
                try { if (ps != null) ps.close(); } catch (Exception ex) {}
                try { if (fis != null) fis.close(); } catch (Exception ex) {}
            }
        }
        
    } else {
        JOptionPane.showMessageDialog(this, 
            "Name nicht angegeben!\n");
    }
}//GEN-LAST:event_jBEinfuegenActionPerformed
private void jBSuchenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSuchenActionPerformed
// TODO add your handling code here:
    PreparedStatement st = null;
    ResultSet rs = null;
    
    String query = "SELECT name,bild FROM sqlImage WHERE name = ?";
    
    if (jTFName.getText().length() > 0) {
        String htmlName = "";
        try {
            st = connection.prepareStatement(query);
            st.setString(1, jTFName.getText());
            rs = st.executeQuery();
            rs.next();
            
            htmlName = rs.getString("name");
            
            Blob bl = rs.getBlob("bild");
            BufferedInputStream bis = new BufferedInputStream(bl.getBinaryStream());
            Image obild = javax.imageio.ImageIO.read(bis);
            Image htmlBild = obild.getScaledInstance(75,100, Image.SCALE_SMOOTH);
            
            jLBild.setIcon(new ImageIcon(htmlBild));
            jLBild.setText("");
            
            setTextausgabe(htmlName, htmlBild);
            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.toString());
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception ex) {}
            try { if (st != null) st.close(); } catch (Exception ex) {}
        }
    } else {
        JOptionPane.showMessageDialog(this, 
            "Kein Eintrag im Feld Name!\n");
        return;
    }
    
}//GEN-LAST:event_jBSuchenActionPerformed
private void setTextausgabe(String name, Image bild) {
    String html = "<html><table border=0>" +
        "<tr><td>[b]Name:[/b] " + name + "
</td>" +
        "<td><img src=bild></td></tr>" +
        "</table></html>";
    
    jTextausgabe.setContentType("text/html");
    jTextausgabe.setText(html);
    jTextausgabe.setEditable(false);
}
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SqlImage dialog = new SqlImage(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBEinfuegen;
    private javax.swing.JButton jBSuchen;
    private javax.swing.JLabel jLBild;
    private javax.swing.JLabel jLName;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTFName;
    private javax.swing.JTextPane jTextausgabe;
    // End of variables declaration//GEN-END:variables
}