mysql用blob添加二进制文件,歌曲,图片,电影

package Io流;

import Utils.JdbcUtils;
import org.junit.Test;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Blob字节
 * 1、MySQL有四种BLOB类型:
 *   ·tinyblob:仅255个字符
 *   ·blob:最大限制到65K字节
 *   ·mediumblob:限制到16M字节
 *   ·longblob:可达4GB
 */
public class Demo09 {
    @Test
    public void test(){
        String sql = null;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int updateRow = 0;
        FileInputStream fis = null;
        try {
            sql = "insert into data_blob values (?,?,?)";
            con = JdbcUtils.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1,1);
            ps.setString(2,"tom");
            File file = new File("d:\\可可托海的牧羊人 - 王琪.mp3");
            fis = new FileInputStream(file);
            ps.setBinaryStream(3,fis,file.length());
            updateRow = ps.executeUpdate();
            if (updateRow > 0){
                System.out.println("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(con,ps,rs);
        }
    }
    @Test
    public void test1(){
        String sql = null;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int updateRow = 0;
        FileOutputStream fos = null;
        int len = 0;

        try {
            sql = "select * from data_blob where id=?";
            con = JdbcUtils.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1,1);
            rs = ps.executeQuery();
            if (rs.next()){
                InputStream songs = rs.getBinaryStream("songs");
                fos = new FileOutputStream("resoures\\歌曲.mp4");
                byte[] bytes = new byte[1024];
                while ((len = songs.read(bytes))!= -1){
                    fos.write(bytes,0,len);
                }
            }
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(con,ps,rs);
        }
    }
}
posted @ 2021-01-24 21:25  dgxacc  阅读(116)  评论(0)    收藏  举报