JDBC:LOB---BLOB、CLOB

Oracle LOB

LOB ,即 LargeObjects (大对象) 是用来存储大量的二进制和文本数据的一种数据类型 (一个 LOB 字段可存储可多达 4GB 的数据)。
LOB 分为两种类型:内部 LOB 和外部 LOB
内部 LOB
          将数据以字节流的形式存储在数据库的内部。因而,内部 LOB 的许多操作都可以参与事务,也可以像处理普通数据一样对其进行备份和恢复操作。
         Oracle 支持三种类型的内部 LOB
                 • BLOB (二进制数据)  
                 • CLOB (单字节字符数据) 
                 • NCLOB (多字节字符数据)。
CLOB NCLOB 类型适用于存储超长的文本数据, BLOB 字段适用于存储大量的二进制数据,如图像、视频、音频,文件等
目前只支持一种外部 LOB 类型,即 BFILE 类型。在数据库内,该类型仅存储数据在操作系统中的位置信息,而数据的实体以外部文件的形式存在于操作系统的文件系统中。因而,该类型所表示的数据是只读的,不参与事务。该类型可帮助用户管理大量的由外部程序访问的文件。

MySQL
BLOB

MySQL 中, BLOB 是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。


•MySQ
L 的四种 BLOB 类型 ( 除了在存储的最大信息量上不同外,他们是等同的 )
实际使用中根据需要存入的数据大小定义不同的 BLOB 类型。
需要注意的是:如果存储的文件过大,数据库的性能会下降。

JDBC读写BLOB

    /**
     * 读取 blob 数据:
     * 1. 使用 getBlob 方法读取到 Blob 对象
     * 2. 调用 Blob 的 getBinaryStream() 方法得到输入流。再使用 IO 操作即可.
     */
    @Test
    public void readBlob(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = JDBCTools.getConnection();
            String sql = "SELECT id, name customerName, email, birth, picture "
                    + "FROM customers WHERE id = 13";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            
            if(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                
                System.out.println(id + ", " + name  + ", " + email);
                Blob picture = resultSet.getBlob(5);
                
                InputStream in = picture.getBinaryStream();

                System.out.println(in.available());
                
                OutputStream out = new FileOutputStream("flower.jpg");
                
                byte [] buffer = new byte[1024];
                int len = 0;
                while((len = in.read(buffer)) != -1){
                    out.write(buffer, 0, len);
                }
                
                in.close();
                out.close();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCTools.releaseDB(resultSet, preparedStatement, connection);
        }
    }
    
    /**
     * 插入 BLOB 类型的数据必须使用 PreparedStatement:因为 BLOB 类型
     * 的数据时无法使用字符串拼写的。
     *
     * 调用 setBlob(int index, InputStream inputStream)
     */
    @Test
    public void testInsertBlob(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = JDBCTools.getConnection();
            String sql = "INSERT INTO customers(name, email, birth, picture)"
                    + "VALUES(?,?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            
            preparedStatement.setString(1, "ABCDE");
            preparedStatement.setString(2, "abcde@atguigu.com");
            preparedStatement.setDate(3,
                    new Date(new java.util.Date().getTime()));
            
            InputStream inputStream = new FileInputStream("Hydrangeas.jpg");
            preparedStatement.setBlob(4, inputStream);

            
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCTools.releaseDB(null, preparedStatement, connection);
        }
    }





获取图片二进制再缩放


public class OracleQueryBean {

    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";

 

    private Connection myConnection = null;

   

    /*图片表名*/

    private String strTabName;

    /*图片ID字段名*/

    private String strIDName;

    /*图片字段名*/

    private String strImgName;

    /**

     * 加载java连接Oraclejdbc驱动

     */

    public OracleQueryBean(){

        try{

            Class.forName(oracleDriverName);

        }catch(ClassNotFoundException ex){

            System.out.println("加载jdbc驱动失败,原因:" + ex.getMessage());

        }

    }

    /**

     * 获取Oracle连接对象

     * @return Connection

     */

    public Connection getConnection(){

        try{

        //用户名+密码; 以下使用的Test就是Oracle里的表空间

        //从配置文件中读取数据库信息

        GetPara oGetPara = new GetPara();

        String strIP = oGetPara.getPara("serverip");

        String strPort = oGetPara.getPara("port");

        String strDBName = oGetPara.getPara("dbname");

        String strUser = oGetPara.getPara("user");

        String strPassword = oGetPara.getPara("password");

       

        this.strTabName = oGetPara.getPara("tablename");

        this.strIDName = oGetPara.getPara("imgidname");

        this.strImgName = oGetPara.getPara("imgname");

       

        String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;

            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);

        }catch(Exception ex){

            System.out.println("Can not get connection:" + ex.getMessage());

            System.out.println("请检测配置文件中的数据库信息是否正确." );

        }

        return this.myConnection;

    }

    /**

     * 根据图片在数据库中的ID进行读取

     * @param strID 图片字段ID

     * @param w      需要缩到的宽度

     * @param h      需要缩到高度

     * @return       缩放后的图片的byte数据

     */

    public byte[] GetImgByteById(String strID, int w, int h){

    //System.out.println("Get img data which id is " + nID);

    if(myConnection == null)

         this.getConnection();

    byte[] data = null;

    try {

            Statement stmt = myConnection.createStatement();

            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);

           

            StringBuffer myStringBuffer = new StringBuffer();

            if (myResultSet.next()) {

                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);

                InputStream inStream = blob.getBinaryStream();

                try {

                    long nLen = blob.length();

                    int nSize = (int) nLen;

                    //System.out.println("img data size is :" + nSize);

                    data = new byte[nSize];

                    inStream.read(data);

                    inStream.close();

                } catch (IOException e) {

                    System.out.println("获取图片数据失败,原因:" + e.getMessage());

                }

               

                data = ChangeImgSize(data, w, h);

            }

            System.out.println(myStringBuffer.toString());

            myConnection.commit();

            myConnection.close();

        } catch (SQLException ex) {

            System.out.println(ex.getMessage());

        }

        return data;

    }

   

    /**

     * 根据图片在数据库中的ID进行读取,显示原始大小的图片

     * @param    strID   图片字段ID

     * @return   读取后的图片byte数据

     */

    public byte[] GetImgByteById(String strID){

    //System.out.println("Get img data which id is " + nID);

    if(myConnection == null)

         this.getConnection();

    byte[] data = null;

    try {

            Statement stmt = myConnection.createStatement();

            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);

           

            StringBuffer myStringBuffer = new StringBuffer();

            if (myResultSet.next()) {

                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);

                InputStream inStream = blob.getBinaryStream();

                try {

                    long nLen = blob.length();

                    int nSize = (int) nLen;

                    data = new byte[nSize];

                    inStream.read(data);

                    inStream.close();

                } catch (IOException e) {

                    System.out.println("获取图片数据失败,原因:" + e.getMessage());

                }

            }

            System.out.println(myStringBuffer.toString());

            myConnection.commit();

            myConnection.close();

        } catch (SQLException ex) {

            System.out.println(ex.getMessage());

        }

        return data;

    }

   

    /**

     * 缩小或放大图片

     * @param data   图片的byte数据

     * @param w      需要缩到的宽度

     * @param h      需要缩到高度

     * @return

     */

    private byte[] ChangeImgSize(byte[] data, int nw, int nh){

    byte[] newdata = null;

    try

         BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));

            int w = bis.getWidth();

            int h = bis.getHeight();

            double sx = (double) nw / w;

            double sy = (double) nh / h;

            AffineTransform transform = new AffineTransform();

            transform.setToScale(sx, sy);

            AffineTransformOp ato = new AffineTransformOp(transform, null);

            //原始颜色

            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);

            ato.filter(bis, bid);          

            //转换成byte字节

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            ImageIO.write(bid, "jpeg", baos);

            newdata = baos.toByteArray();

    }catch(IOException e){ 

         e.printStackTrace(); 

    } 

    return newdata;

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值