java - 为什么这段java代码无法将图像保存到mysql数据库中?

标签 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页面中,我编写了以下代码,以便可以将这些图像更新到数据库(在这里,我之前在数据库列中没有保存图像,所以我想更新那些没有图像的列)。我在参数中保留了相同的变量名称;即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数据库中。

最佳答案

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){
 }

关于java - 为什么这段java代码无法将图像保存到mysql数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948975/

相关文章:

java - 如何防止重复。 Java、SQL

php - 从mysql的不同列中选择值,我怎么知道哪个是哪个?

java - jsp、连接池和mysql

使用 Spring Boot 项目时,JSP 文件未部署到 Pivotal Web Services

java - 如何滚动到 RecyclerView 的底部?滚动到位置不起作用

java - DatabaseException - 无法将 java.lang.String 类型的对象转换为 com.appmaster.akash.messageplus.Results 类型

php - 如何关联 php mysql 中不同表的值并显示这些值?

java - Spring MVC - 无法为 JSP 编译类

java - 如何设置xpath的第二个节点

java - 如何匹配任意数量的大写字母?