Note that there are some explanatory texts on larger screens.

plurals
  1. POSaving an image in MySQL from Java
    text
    copied!<p>I am trying to save images in MySQL database from a Java swing application. I am using JFileChsoser to get the path of the image. Then after that converting the file so that it can be saved in the MySQL column which is of BLOB type. But every image I try to save does not save properly or get converted properly. Could someone tell me what I'm doing wrong over here?</p> <pre><code>private void btn_choosepicActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser picchooser = new JFileChooser(); picchooser.setDialogTitle("Select Image"); picchooser.showOpenDialog(null); File pic=picchooser.getSelectedFile(); path= pic.getAbsolutePath(); txt_path.setText(path.replace('\\','/')); try{ File image = new File(path); FileInputStream fis = new FileInputStream(image); ByteArrayOutputStream baos= new ByteArrayOutputStream(); byte[] buff = new byte[1024]; for(int readNum; (readNum=fis.read(buff)) !=-1 ; ){ baos.write(buff,0,readNum); } userimage=baos.toByteArray(); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } } </code></pre> <p>And then after this Im saving it to the database like so.</p> <pre><code>private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) { String user= txt_username.getText(); try{ String sql="insert into imgtst (username,image) values ('"+user+"','"+userimage+"')"; pst=con.prepareStatement(sql); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "Saved"); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } } </code></pre> <p>and I have declared the variable userimage and path as a global variables</p> <pre><code>String path=null; byte[] userimage=null; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload