微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,1024))!=-1){     os.write(b,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();  } }}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐