jdbc将图片(二进制文件如电影,音乐等)从数据库取出

来源:互联网 发布:无法读取碳粉盒数据 编辑:程序博客网 时间:2024/06/05 23:45

//jdbc将图片(二进制文件如电影,音乐等)从数据库取出,我是放在了d盘,一般直接在网站上展示即可

package chap06.sec01;



import java.io.File;
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.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import model.Book;
import util.DbUtil;


public class Demo2 {
private static DbUtil dbUtil=new DbUtil();
private static int addBook(Book book) throws SQLException, FileNotFoundException{//插入图书

String sql="insert into t_book values(null,?,?,?,?,?,?)"; 
Connection con= dbUtil.getCon();
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, book.getBookName());
pstmt.setFloat(2, book.getPrice());
pstmt.setString(3, book.getAuthor());
pstmt.setInt(4, book.getBookTypeId());
File context=book.getContext();
InputStream in=new FileInputStream(context);
pstmt.setAsciiStream(5, in,context.length());//给第5个坑设置值
File pic=book.getPic();
InputStream in_pic=new FileInputStream(pic);
pstmt.setBinaryStream(6, in_pic, pic.length());//给第6个坑设置值

int result=pstmt.executeUpdate();
dbUtil.closeCon(pstmt, con);
return result;
}

public static void getBook(int id) throws SQLException, IOException{
Connection conn=dbUtil.getCon();
String sql="select * from t_book where id=?";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setInt(1, id);
ResultSet rs=pre.executeQuery();
if(rs.next()){
String bookName=rs.getString("bookName");
float price=rs.getFloat("price");
String author=rs.getString("author");
int bookTypeId=rs.getInt("bookTypeId");
Clob c=rs.getClob("context");
String context=c.getSubString(1, (int) c.length());
Blob b=rs.getBlob("pic");//
OutputStream out=new FileOutputStream(new File("d:/linshi.png"));//linshi.png为临时创建存放图片的

out.write(b.getBytes(1, (int)b.length()));
out.close();

System.out.println("图书名称:"+bookName);
System.out.println("图书价格:"+price);
System.out.println("图书作者:"+author);
System.out.println("图书类型ID:"+bookTypeId);
System.out.println("图书内容:"+context);
}
dbUtil.closeCon(pre, conn);
}


public static void main(String[] args) throws Exception {
// File context=new File("C:/helloworld.txt"); 
// File pic=new File("C:/ok.png"); 
// Book book=new Book("javaqwe4",444,"李四4",4,context,pic);
// try {
// int result =addBook(book);
// if(result==1){
// System.out.println("添加成功");
// }
// else{
// System.out.println("添加失败");
// }
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println("hellowold");
getBook(18);//18为图书id根据id查其中的图片
}
}
1 0
原创粉丝点击