加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 15:44:08 所属栏目:MsSql教程 来源:网络整理
导读:? 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;
?

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();??}?}}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读