java文件上传数据库中_java 文件上传到数据库为blob

这篇博客展示了如何使用Java将大文件(如图片)存储到MySQL数据库的Blob字段中,但提到MySQL的Blob类型可能不支持超过65535字节的数据,而其他大型数据库系统则支持。文章提供了详细的代码示例,演示了如何通过PreparedStatement实现文件的插入操作。
摘要由CSDN通过智能技术生成

其实也没有什么,就拿mysql为例;

现在数据库建表,

让后写一个测试类

经本人测试绝对可用

import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /** *在mysql数据库里成功测试,并且发现mysql的blob数据库不支持存储图片,只支持 *65535字节以下的本本数据存储。不过其他的大型数据库是支持储存图片的. */ public class InsertBlob { public static void main(String[] args) { try{ File f = new File("C:\\bsmain_runtime.log");        long length = f.length();        FileInputStream fis = new FileInputStream("C:\\bsmain_runtime.log");               byte[] imageBytes=new byte[(int)length];              int byteLength=fis.read(imageBytes, 0, (int)length);               ByteArrayInputStream bais=new ByteArrayInputStream(imageBytes);        Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","java"); PreparedStatement pstmt = null;  /* create table mypicture  (name varchar(20),     image blob);     */ pstmt = con.prepareStatement("insert into mypicture(name,image) values(?,?)"); pstmt.setString(1, "001"); pstmt.setBinaryStream(2,bais,byteLength); pstmt.executeUpdate(); System.out.println("file length:"+length); System.out.println("byte length:"+byteLength); System.out.println("插入成功."); }catch(Exception e){ e.printStackTrace(); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值