java之二进制存取图片(MySQL数据库)

闲来无事,弄了个二进制读取图片,而非本地路径读取,仅供学习之用,大家多多指教!!

第一步建表:

SQL:

createtableimages_info(

image_idint(10)notnullauto_incrementprimarykey,

image_namevarchar(255),

image_sizeint,

image_datedatetime,

image_typevarchar(10),

image_datalongblob,

image_descriptionvarchar(255),

authorvarchar(100));

修改图片传入最大值:

mySQL安装目录下的my-small.ini文件里面的max_allowed_packet=1M修改成:

max_allowed_packet=32M

(参考:在Linux系统中它的配置在mycnf文件中加入max_allowed_packet=32M就行

在命令行配置的方法是:mysqld-nt--console--max_allowed_packet=32M)

第二步编写java代码:

1.插入图片到数据库中代码片段:

privateConnectionconn=null;

privatePreparedStatementpstmt=null;

privatestaticfinalStringsql="INSERTINTOimages_info(image_id,image_name,image_size,image_date,image_type,image_description,author,image_data)VALUES(null,?,?,now(),?,?,?,?)";

publicbooleanaddPhoto(ImageVoimageVo){

booleanflag=false;

try{

//将文件转换为流文件

InputStreamphotoStream=newFileInputStream(imageVo.getImageData());

//获取数据库连接

conn=ConnectionFactory.getConnection();

pstmt=conn.prepareStatement(sql);

pstmt.setString(1,imageVo.getImageName());

pstmt.setInt(2,imageVo.getImageSize());

pstmt.setString(3,"jpg");//图片类型

pstmt.setString(4,imageVo.getDescription());

pstmt.setString(5,imageVo.getAuthor());

pstmt.setBinaryStream(6,photoStream,(int)imageVo.getImageData().length());

introw=pstmt.executeUpdate();

if(row==1){

flag=true;

}

}catch(FileNotFoundExceptionfe){

fe.printStackTrace();

}catch(SQLExceptione){

e.printStackTrace();

}finally{

if(null!=pstmt){

try{pstmt.close();}

catch(SQLExceptione){

e.printStackTrace();

}

}

if(null!=conn){

try{conn.close();}

catch(SQLExceptione){

e.printStackTrace();

}

}

}

returnflag;

}

2.从数据库读取图片信息

privateConnectionconn=null;

privatePreparedStatementpstmt=null;

privateResultSetrs=null;

//查询具体图片数据流格式

privatestaticfinalStringdata_sql="selectimage_datafromimages_infowhereimage_id=?";

publicvoidReadImage(intimageId,StringimageName){

FileOutputStreamfos=null;

InputStreamin=null;

byte[]Buffer=newbyte[4096];

try{

conn=ConnectionFactory.getConnection();

pstmt=conn.prepareStatement(data_sql);

pstmt.setInt(1,imageId);

rs=pstmt.executeQuery();

rs.next();

Filefile=newFile(imageName);

if(!file.exists()){

file.createNewFile();//如果文件不存在,则创建

}

fos=newFileOutputStream(file);

in=rs.getBinaryStream("image_data");

intsize=0;

while((size=in.read(Buffer))!=-1){

fos.write(Buffer,0,size);

}

}catch(SQLExceptione){

e.printStackTrace();

}catch(IOExceptionioe){

ioe.printStackTrace();

}finally{

//关闭数据流

if(null!=rs){

try{

rs.close();

}catch(SQLExceptione){

e.printStackTrace();

}

}

if(null!=pstmt){

try{

pstmt.close();

}catch(SQLExceptione){

e.printStackTrace();

}

}

if(null!=conn){

try{

conn.close();

}catch(SQLExceptione){

e.printStackTrace();

}

}

}

}

对象类属性:

StringimageId;

StringimageName;

intimageSize;

DateimageDate;

StringimageType;

Stringdescription;

Stringauthor;

FileimageData;

相关推荐