您的位置:首页 > 数据库

图片在数据库中的存取

2013-06-02 13:09 232 查看

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: