Saving an image in MySQL from Java

前端 未结 1 965
傲寒
傲寒 2020-12-15 14:26

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

相关标签:
1条回答
  • 2020-12-15 15:13

    You are converting the byte[] to a String in your sql statement, and you will end up with incorrect data.

    The right way to use a BLOB would be to pass the InputStream itself. You can use the FileInputStream you are using to read the file.

    File image = new File(path);
    FileInputStream fis = new FileInputStream ( image );
    
    String sql="insert into imgtst (username,image) values (?, ?)";
    pst=con.prepareStatement(sql);
    
    pst.setString(1, user);
    pst.setBinaryStream (2, fis, (int) file.length() );
    

    When you retrieve it back you can similarly get an InputStream from the ResultSet:

    InputStream imgStream = resultSet.getBinaryStream(2); 
    
    0 讨论(0)
提交回复
热议问题