10 图片操作(BLOB)

import java.io.*;
import java.sql.*;

/*
 * 测试BLOB二进制大对象的使用
 */
public class TestBLOB{
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream is = null;
        OutputStream os = null;
        
        try {
            //1:加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            
            //2:建立连接(连接对象内部其实包含Socket对象,是一个远程的连接,比较耗时,这是Connection对象管理的一个要点)
            //真正的开发中,都会使用连接池来管理对象
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test","root","123456");
            
            //将图片插入到数据库
            ps = conn.prepareStatement("insert into user (name,age) values (?,?)");
            ps.setObject(1, "b");
            ps.setBlob(2, new FileInputStream("E:/1.png"));
            
            ps.execute();
            
            ps = conn.prepareStatement("select * from user where name=?");
            ps.setObject(1, 2);
            
            rs = ps.executeQuery();
            while(rs.next()){
                Blob b = rs.getBlob("age");
                is = b.getBinaryStream();
                
                //将数据库中的图片,写到指定路径中
                os = new FileOutputStream("e:/b.png");
                int temp = 0;
                while((temp = is.read()) != -1){
                    os.write(temp);
                }
            }
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            //关闭顺序遵循:ResultSet-->Statement->Connection
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容