将图片存入数据库和下载到本地

存入:成功将一张图片文件存入数据库

import java.sql.*;
import java.io.*;
public class Imagedata{
 public static void main(String[] args) {
  try {
   Class.forName("com.mysql.jdbc.Driver");//加载驱动
   Connection conn=DriverManager.getConnection("jdbc:mysql://192.168.24.75:3306/photoserver?useUnicode=true&characterEncoding=utf-8","root","123");//建立数据库链接
 File file=new File("mark.png");//指定入库的文件


   FileInputStream fis=new FileInputStream(file);//创建输入流对象这里可以将fis想象成一个管道  这个管道架在file中存的路径所对应的图片上  将这个图片化成的二进制数据装入管道fis
   PreparedStatement ps=conn.prepareStatement("insert into photo18 values(?,?)"); //通过实例对象cn将SQL语句存入 PS中带入SQL数据库中
   ps.setBinaryStream(1,fis,(int)file.length());
   ps.setString(2,file.getName());
   ps.executeUpdate();//执行该数据库语句最终将图片分解成二进制数据放入表中的PHOTO字段
   
   System.out.println("图片入库成功");
 
   ps.close();
   fis.close();
   conn.close();
 
  }catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
  }
}
/**建库信息**/
 /*create database 表名 ;
/**建表信息**/
/*
 use 表名;
 create table image(image longblob,name char(30));
 */


读取:

public class Test { 
static String dbURL = "jdbc:mysql://localhost:3306/photoserver"; 
static String userID = "root"; 
static String passwd = "123"; 
public static void main(String[] args)throws Exception {
File f = new File(".\\"+File.separator+"photo") ;// 实例化File类的对象
     f.mkdir() ; // 创建文件夹
Class.forName("com.mysql.jdbc.Driver"); 
 Connection conn=(Connection) DriverManager.getConnection(dbURL, userID, passwd); 
 conn.setAutoCommit(false); 


 String sql2 = "SELECT image,name FROM image "; 
 PreparedStatement stmt2 = conn.prepareStatement(sql2); 
 ResultSet resultSet = stmt2.executeQuery(); 
 while (resultSet.next()) { 
 String name = resultSet.getString(2); 
 String description = resultSet.getString(1); 
 File image2 = new File("photo/" + name); 
 FileOutputStream fos = new FileOutputStream(image2); 
 byte[] buffer = new byte[1]; 
 InputStream is = resultSet.getBinaryStream(1); /*read(byte[] b),从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。write(byte[] b),
将 b.length 个字节从指定的 byte 数组写入此输出流。 */
 System.out.println("成功将:"+name+":写入指定文件夹下");
 
 while (is.read(buffer) > 0) { 
 fos.write(buffer); 
 } 
 fos.close(); 
 } 
conn.close(); 
 }

/**建库信息**/
 /*create database 表名 ;
/**建表信息**/
/*
 use 表名;
 create table image(image longblob,name char(30));
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值