无论在哪个数据库里,blob类型的数据和其他类型的数据存储和获取方式是不一样的。
笔者最近在用mysql做开发,期间也遇到了这个问题。经过从网上搜索和查阅,终于把问题搞定了!现整理出来。。。
笔者是想数据库里插入图片。
数据表简写如下:
create table Dish {
int id;
blob photo;
};
下面是从数据库里写的方法:
String filepath = (String)session.getAttribute("file");//这里获得的是用jspsmartupload上传的文件的路径
File file = new File(filepath);
FileInputStream fin = new FileInputStream(file);
dataBS = new blobConn();
con = dataBS.getConn();
File file = new File(filepath);
FileInputStream fin = new FileInputStream(file);
dataBS = new blobConn();
con = dataBS.getConn();
String erpsql = "insert into Dish values(?,?)";
PreparedStatement stmt = con.prepareStatement(erpsql);
stmt.setString(2,String.valueOf(id));
stmt.setBinaryStream(3,fin,(int)file.length());//想数据库里插入是很简单的,就一行,但这种方法只有mysql可以用
stmt.executeUpdate();
fin.close();
stmt.close();
con.close();
PreparedStatement stmt = con.prepareStatement(erpsql);
stmt.setString(2,String.valueOf(id));
stmt.setBinaryStream(3,fin,(int)file.length());//想数据库里插入是很简单的,就一行,但这种方法只有mysql可以用
stmt.executeUpdate();
fin.close();
stmt.close();
con.close();
下面是从数据库里读的方法:
1.BufferedInputStream inputimg = null;
try {
Connection con = sqlDS.getConnection();//简写,获得数据库连接
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select from Dish where id = 11");
if(rs.next()){
java.sql.Blob blob = (java.sql.Blob)rs.getBlob("photo");
input = new BufferedInputStream(blob.getBinaryStream);
}
BufferedImage image = null;
image = javax.imageio.ImageIo.read(input);
ServlerOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
input.close();
}catch(Exception e) {
e.printStackTrace();
}
2.
if(rs.next()){
res.setContentType ("image/jpeg;charset=GB2312");//HttpServletResponse res
ServletOutputStream out = res.getOutputStream ();
BufferedInputStream jpgData = new BufferedInputStream (rs.getBinaryStream ("photo"));
byte [] buf = new byte [4*1024];
int len;
ServletOutputStream out = res.getOutputStream ();
BufferedInputStream jpgData = new BufferedInputStream (rs.getBinaryStream ("photo"));
byte [] buf = new byte [4*1024];
int len;
if(jpgData.available () <= 0x0)//判断数据库里存放图片的字段是否有值,可以进行其他处理
res.sendRedirect ("/images/nophoto.gif");
while((len = jpgData.read (buf, 0, buf.length)) != -1)
out.write (buf, 0, len);
res.sendRedirect ("/images/nophoto.gif");
while((len = jpgData.read (buf, 0, buf.length)) != -1)
out.write (buf, 0, len);
}
3.
if(rs.next()){
res.setContentType("image/jpeg");
ServletOutputStream out=res.getOutputStream();
InputStream in=rs.getBinaryStream("photo");
byte buff[]=new byte[1024];
int i;
while((i=in.read(buff))!=-1){
out.write(buff);
}
in.close();
out.close();
ServletOutputStream out=res.getOutputStream();
InputStream in=rs.getBinaryStream("photo");
byte buff[]=new byte[1024];
int i;
while((i=in.read(buff))!=-1){
out.write(buff);
}
in.close();
out.close();
}