JDBC进行处理大文件和批处理

package cn.itcast.demo4;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.rowset.serial.SerialBlob;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import cn.itcast.demo3.JdbcUtils;

/**
 * 大数据
 * @author Administrator
 *
 */
public class Demo4 {
    
    /**
     * 将mp3保存到数据库中
     */
    @Test
    public void fun1() throws Exception{
        /*
         *得到Connection
         *给出sql模板,创建pstmt
         *设置sql模板中的参数
         *调用pstmt中的executeUpdate()执行 
         */
        Connection con=JdbcUtils.getConnection();
        String sql="INSERT INTO tab_bin VALUES(?,?,?)";
        PreparedStatement pstmt=con.prepareCall(sql);
        
        pstmt.setInt(1, 1);
        pstmt.setString(2, "陈粒-奇妙能力歌.mp3");
        /**
         * 需要得到Blob
         * 我们有文件,目标是Blob
         * 先将文件变成byte[]
         * 再使用byte[]创建Blob
         */
        
        byte[] bytes=IOUtils.toByteArray(new FileInputStream("E:\KuGou\陈粒 - 奇妙能力歌.mp3"));
        Blob blob=new SerialBlob(bytes);
        pstmt.setBlob(3, blob);
        
        pstmt.executeUpdate();
         
    }
    
    @Test
    public void fun2() throws Exception{
        Connection conn=JdbcUtils.getConnection();
        
        String sql="SELECT * FROM tab_bin";
        PreparedStatement pstmt=conn.prepareStatement(sql);
        
        ResultSet rs=pstmt.executeQuery();
        
        if(rs.next()){
            Blob blob=rs.getBlob("resource");
            InputStream in=blob.getBinaryStream();
            OutputStream out=new FileOutputStream("e:/"+rs.getString("bname"));
            IOUtils.copy(in, out);
        }
    }
}

JDBC进行批处理:

package cn.itcast.demo5;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

import cn.itcast.demo3.JdbcUtils;

/**
 * 批处理
 * @author Administrator
 *
 */
public class Demo5 {
    
    /**
     * pstmt对象内部有集合
     * 1、用循环疯狂向pstmt中添加sql参数,它自己有模板,使用一组参数和模板可以匹配出一条sql语句
     * 2、调用它的执行批方法,完成向数据库发送!
     */
    @Test
    public void fun5() throws SQLException{
        Connection conn=JdbcUtils.getConnection();
        String sql="INSERT INTO t_stu VALUES (?,?,?,?)";
        PreparedStatement pstmt=conn.prepareStatement(sql);
        
        for(int i=0;i<1000;i++){
            pstmt.setInt(1, i+1);
            pstmt.setString(2, "stu_"+i);
            pstmt.setInt(3, i);
            pstmt.setString(4, i%2==0?"男":"女");
            
            pstmt.addBatch();
        }
        
        long start=System.currentTimeMillis();
        pstmt.executeBatch();
        long end=System.currentTimeMillis();
        System.out.println(end - start );
    }
}
原文地址:https://www.cnblogs.com/aigeileshei/p/5712344.html