读书人

【MySql】数据库写下图片和读出图片

发布时间: 2012-07-04 19:33:55 作者: rapoo

【MySql】数据库写入图片和读出图片

//写入图片到数据库static void insert() throws Exception{String sql ="insert into pics (pic) values (?)";Connection conn=JdbcUtilSingle.getConnection();PreparedStatement pst=conn.prepareStatement(sql);File file = new File("p_large_CuRa_47110000afc8121a.jpg");InputStream inputstream = new BufferedInputStream(new FileInputStream(file));pst.setBinaryStream(1, inputstream, (int)file.length());//说明:这里一定要转化为int,否则会报错,length()返回值为long类型的//setBinaryStream(1, inputstream,(long)file.length());int i = pst.executeUpdate();System.out.println(i);JdbcUtilSingle.free(null, pst, conn);}//读出图片信息static void write() throws Exception{String sql="select * from pics ";Connection conn=JdbcUtilSingle.getConnection();PreparedStatement pst=conn.prepareStatement(sql);ResultSet rs=pst.executeQuery();File file = new File("mypic.jpg");while(rs.next()){//Blob blob = rs.getBlob(1);//InputStream in = blob.getBinaryStream();//上面行的作用和下面行相同InputStream in = rs.getBinaryStream(1);OutputStream out = new BufferedOutputStream(new FileOutputStream(file));byte buff[]= new byte[1024];//入文件for(int i=0;(i=in.read(buff))>0;){out.write(buff, 0, i);}}JdbcUtilSingle.free(rs, pst, conn);
?

读书人网 >其他数据库

热点推荐