SQLServer数据库中插入、读取图片

 

package zcl.todb.db;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class OperationDB {
 private ConnectDB db;
 public OperationDB(){
  this.db=new ConnectDB();
 }
 public boolean insertImage(String filename){//想数据库中插入图片的方法,filename是图片的名字。
  boolean res=false;
  Connection con=this.db.getConnectDB();
  String sql="insert into image values(?,?)";
  try {
   PreparedStatement pst=con.prepareStatement(sql);
   pst.setString(1, "image");
   FileInputStream file=new FileInputStream(filename);
   pst.setBinaryStream(2, file, file.available());
   pst.executeUpdate();
   res=true;
   pst.close();
   this.db.closeDB(con);
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   System.out.println("文件没有被发现");
  } catch (IOException e) {
   System.out.println("文件IO流出现错误");
  }
  return res;
 }
 public boolean getImage(OutputStream os){//读数据的方法。
  boolean res=false;
  Connection con=this.db.getConnectDB();
  String sql="select * from image where id=?";
  try {
   PreparedStatement pst=con.prepareStatement(sql);
   pst.setInt(1, 5);
   ResultSet rs=pst.executeQuery();
   if(rs.next()){
    InputStream in=rs.getBinaryStream("image");
    byte b[]=new byte [1024];
    int i=0;
    while((i=in.read(b, 0, 1024))!=-1){
     os.write(b, 0, i);
    }
    res=true;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return res;
 }
 public static void main(String[] args) {
  OperationDB op=new OperationDB();
  //if(op.insertImage("D:/temp.png")){//使用上面的方法,进行插入读取SQLServer数据库中的图片
  // System.out.println("图片插入成功!!");
  //}
  try {
   FileOutputStream os=new FileOutputStream("d:/temp0.png");
   if(op.getImage(os)){
    System.out.println("OK");
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值