mysql blob无法显示二进制文件_mysql用blob添加二进制文件,歌曲,图片,电影

本文通过Java示例展示了如何使用Blob类型在MySQL中插入及读取文件数据。具体包括使用FileInputStream将本地文件写入数据库,以及使用FileOutputStream从数据库中读取文件并保存到本地的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值