为什么此Java代码无法将图像保存在mysql数据库中?

时间:2018-10-23 12:22:16

标签: java mysql jsp

我已使用以下代码将BufferedImage作为参数从jsp传递给Java:

 <%BufferedImage citizen = ImageIO.read(new File(add1));%>
        <%BufferedImage degree=ImageIO.read(new File(deg1));%>
<%String available=com.Package1.UpdataStudentInfo.useValues(citizen, degree);%>

“ add1”和“ deg1”是图像的路径。

在Java页面中,我编写了以下代码,以便可以将这些图像更新到数据库(此处,以前在db列中没有保存图像,因此我想更新没有图像的列)。我在变量中保留了相同的变量名;即jsp的BufferedImage公民在Java中是BufferedImage公民,jsp的BufferedImage度在Java中也是BufferedImage度。因此,变量名没有问题。

 try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();   
      try{

              ByteArrayOutputStream os1 = new ByteArrayOutputStream();
    ImageIO.write(citizen, "PNG", os1);
    ByteArrayInputStream citizen_is = new ByteArrayInputStream(os1.toByteArray());

    ByteArrayOutputStream os2 = new ByteArrayOutputStream();
    ImageIO.write(degree, "PNG", os2);
    ByteArrayInputStream degree_is = new ByteArrayInputStream(os2.toByteArray());

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
PreparedStatement stmt=con.prepareStatement("UPDATE student SET citizenship=?, degree=? WHERE sn=? ");
                stmt.setBlob(1, (Blob) citizen_is);
                     stmt.setBlob(2, (Blob) degree_is);
                     stmt.setInt(3, p);



int x=stmt.executeUpdate();

                 con.close();
}

我也有catch语句来处理异常。但是没有任何例外,也没有任何运行时错误和编译时错误。但是图像未存储在数据库中。

请帮我将这两个映像存储在mysql数据库中。

1 个答案:

答案 0 :(得分:0)

String updateSQL = "UPDATE student SET citizenship=?, degree=? WHERE sn=? ";
File os1 = new File(filenameImageCitizenShip); //load image as file
File os2 = new File(filenameImageDegree); //load image as file
FileInputStream inputOs1 = new FileInputStream(os1);
FileInputStream inputOs2 = new FIleInputStream(os2);
try{
    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
    PreparedStatement pstmt = conn.prepareStatement(updateSQL);
    pstmt.setBinaryStream(1,os1);
    pstmt.setBinaryStream(2,os2); 
    pstmt.setBinaryStream(3,p);
    pstmt.executeUpdate();
  }catch(Exception e){
 }