MySQL中BLOB字段类型介绍
MySQL中,BLOB是个类型系列,BLOB类型的字段用于存储二进制数据包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储文件的最大大小上不同。MySQL的四种BLOB类型
类型 | 大小(单位:字节) |
TinyBlob | 最大 255 |
Blob | 最大 65K |
MediumBlob | 最大 16M |
LongBlob | 最大 4G |
script.sql
create table tblUser
(uid int auto_increment primary key,
uimage mediumblob);
public class ImageTest
{
@Test
public void testSave()
{
try
{
//FileInputStream 从文件系统中的某个文件中获得输入字节
//FileInputStream 用于读取诸如图像数据之类的原始字节流
InputStream is = new FileInputStream("/home/soft02/Test/4.jpg");
byte[] image=new byte[is.available()];
//从此输入流中将最多 iamge.length 个字节的数据读入一个 byte 数组中
is.read(image);
is.close();
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://10.0.5.98:3306/test","root","root");
PreparedStatement stat=conn.prepareStatement("insert into tblUser (uimage) values (?)");
stat.setBytes(1,image);
stat.executeUpdate();
stat.close();
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class ImageAction implements Action
{
private int imageid;
public int getImageid()
{
return imageid;
}
public void setImageid(int imageid)
{
this.imageid = imageid;
}
public String execute() throws Exception
{
HttpServletResponse response=ServletActionContext.getResponse();
ServletOutputStream sos=response.getOutputStream();
byte[] image=null;
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://10.0.5.98:3306/test","root","root");
Statement stat=conn.createStatement();
ResultSet rset=stat.executeQuery("select uimage from tblUser where uid="+imageid);
if(rset.next())
image=rset.getBytes("uimage");
rset.close();
stat.close();
conn.close();
sos.write(image);
return null;
}
}
struts.xml
<action name="readimage" class="itany.action.ImageAction"/>
index.jsp
<!-- index.jsp?imgid=1 -->
<a href="success.jsp"><img src="readimage.itany?imageid=${param.imgid}"/></a>