如何将文本以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();

      }

   }

}

posted @ 2014-10-30 15:39  静坐观雨  阅读(2978)  评论(0编辑  收藏  举报