如何将文本以BLOB类型存入数据库并取出

如何将文本以BLOB类型存入数据库并取出

BLOB类型的使用

java完整代码

import java.io.*;

import java.sql.*;

 

public class test {

   static public  void save() throws SQLException{ 

      Connection conn = DB.getConn();              //连接个人数据库

      try

        File file = new File("g:\\1.txt"); //要转换的文件的所在路径

        FileInputStream inputStream = new FileInputStream(file); 

        String sql="insert into save_image(image) values(?)";//存入数据库的SQL语句在执行的时候一定要用prepareStatement 

        PreparedStatement statement = conn.prepareStatement(sql);

        statement.setBinaryStream(1, inputStream,(int)file.length()); 

        statement.executeUpdate(); 

 

      } catch (FileNotFoundException e) { 

        e.printStackTrace(); 

      } catch (SQLException e) { 

        e.printStackTrace(); 

      } 

 

   }

   static public void readerJpg() throws SQLException{ 

      Connection conn = DB.getConn();

      String sqlString = "select image from save_image where id=0";//从数据库中读出要还原文件的二进制码,这里我读的是个人数据库id为0的文件 

      File file = new File("E:\\1.txt");   //本地生成的文件 

      if(!file.exists()){ 

        try

           file.createNewFile(); 

        } catch (Exception e) { 

           e.printStackTrace(); 

        } 

      } 

      try

        byte[] Buffer = new byte[1024*5];               //根据文本大小给出字节数组 

        PreparedStatement statement=conn.prepareStatement(sqlString); 

        ResultSet resultSet = statement.executeQuery(); 

        if(resultSet.next()){ 

           FileOutputStream outputStream = new FileOutputStream(file); 

           InputStream iStream = resultSet.getBinaryStream("image");   //去字段用getBinaryStream() 

           int size=0; 

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

              System.out.println(size); 

              outputStream.write(Buffer,0,size);

              System.out.println(new String(Buffer));

           } 

        } 

      } catch (Exception e) { 

        e.printStackTrace(); 

      } 

   } 

 

   public static void main(String[] args) {

      try {

        save();

      } catch (SQLException e) {

        e.printStackTrace();

      }

      try {

        readerJpg();

      } catch (SQLException e) {

        e.printStackTrace();

      }

   }

}

转载于:https://www.cnblogs.com/cbyniypeu/p/4062860.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值