Java在SQL Server存取图片

本想找点代码测试一下在SQL Server中存取图片的方法, 结果狂搜之后才发现,不是基于在jsp中的应用,就是本身过程太复杂,一时半会儿难以看懂,只好自己“亲自”上阵慢慢试了!不曾想原来过程原来是如此之简单!!!基本代码如下:

  File f;
  JFileChooser chooser=new JFileChooser();
  chooser.setCurrentDirectory(new File("."));  //定位当前目录
  
  try {
   //***********写入***********************************************************************
   if(chooser.showOpenDialog(null)==JFileChooser.CANCEL_OPTION){
    System.exit(0);
   }
   f=chooser.getSelectedFile();
   int length=(int)f.length();
   InputStream fin=new FileInputStream(f);
   //SQL Server中只有image类型可以存储二进制数据
   PreparedStatement pstmt=getConn().prepareStatement("INSERT INTO Test(myimage) VALUES(?)");
   pstmt.setBinaryStream(1, fin, length);
   pstmt.executeUpdate();
   pstmt.clearParameters();
   pstmt.close();
   //***********读出保存为文件***********************************************************   
   Statement stmt=getConn().createStatement();
   ResultSet rs=stmt.executeQuery("SELECT myimage FROM Test");
   rs.next();
   Blob blob=rs.getBlob(1);
   if(chooser.showSaveDialog(null)==JFileChooser.CANCEL_OPTION){
    System.exit(0);
   }
   f=chooser.getSelectedFile();
   FileOutputStream fout=new FileOutputStream(f);
   fout.write(blob.getBytes(1, (int)blob.length()));
   fout.flush();
   fout.close();
   stmt.close();

   //***********用JLabel显示出来*********************************************************   
   Statement stmt=getConn().createStatement();
   ResultSet rs=stmt.executeQuery("SELECT myimage FROM Test");
   rs.next();
   InputStream is=rs.getBinaryStream(1);
   byte[] b=new byte[is.available()];
   is.read(b);
   ImageIcon icon=new ImageIcon(b);
   jlbl.setIcon(icon);
   is.close();
   rs.close();
   stmt.close();

  } catch (FileNotFoundException e) {
   System.err.println(e.toString());
   e.printStackTrace();
  } catch (SQLException e) {
   System.err.println(e.toString());
   e.printStackTrace();
  } catch (Exception e) {
   System.err.println(e.toString());
   e.printStackTrace();
  }

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值