zoukankan      html  css  js  c++  java
  • 二进制读取 jdbc

    package com.itheima.clob.test;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import org.junit.Test;
    
    import com.itheima.utils.JdbcUtil;
    
    /**
     * 大二进制数据读写(图片,电影,音乐,字节码文件)  Mysq: blob  longblob
     * @author wangli
     *
     *
     use day16;
     create table testblob(
         id int primary key,
         content longblob
     );
     *
     */
    public class BlobTest02 {
        //写一个图片到数据表中   测试时显示记录,注意  select id from testblob;
        @Test
        public void testAddBlob(){
            Connection con = null;
            PreparedStatement st =null;
            
            try {
                con = JdbcUtil.getConnection();
                String sql="insert into testblob values(?,?)";
                st = con.prepareStatement(sql);
                
                //赋值
                st.setInt(1, 1);
                InputStream is = new FileInputStream("src/1.jpg");//找到src下的文件1.jpg
                st.setBinaryStream(2, is, is.available());
                st.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                JdbcUtil.release(null, st, con);
            }
        }
        
        @Test  //读取一个图片
        public void testReaderblob(){
            Connection con = null;
            PreparedStatement st =null;
            ResultSet rs = null;
            try {
                con = JdbcUtil.getConnection();
                String sql="select * from testblob where id=?";
                st = con.prepareStatement(sql);
                
                //赋值
                st.setInt(1, 1);
                
                //3.读取
                rs = st.executeQuery();
                if(rs.next()){
                    //结果集中有数据
                    InputStream is = rs.getBinaryStream("content");
                    OutputStream os = new FileOutputStream("d:/1.jpg");
                    int len=-1;
                    byte buffer[] = new byte[1024];
                    while((len=is.read(buffer))!=-1){
                        os.write(buffer, 0, len);
                    }
                    os.close();
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                JdbcUtil.release(null, st, con);
            }
        }
    }
  • 相关阅读:
    NUnit
    Fxcop
    msdeploy命令实现远程部署时保留指定文件
    virtualBox 创建新虚拟机
    sharepoint项目部署
    执行批处理文件
    NCover
    配置Web DashBoard
    ccnet+ncover+fxcop+web deploy+mstest
    命令行部署Reporting Services项目
  • 原文地址:https://www.cnblogs.com/baijin05/p/5072927.html
Copyright © 2011-2022 走看看