java保存图片到mysql_java把图片保存到数据库中的例子

本文展示了如何根据客户需求将图片以二进制形式存储到MySQL数据库中,虽然这种方法不推荐,因为可能导致数据库过大且查询效率降低。代码包括了读取数据库中的图片并保存到本地,以及将本地图片写入数据库的示例。
摘要由CSDN通过智能技术生成

图片存储在数据库中是一个客户的要示了,这个方法其实是非常的不好的,因为保存到了数据库中会导致数据库超级大了,但既然做了就给各位分享一下吧.

例子代码

Class.forName("com.mysql.jdbc.Driver");

//System.out.print("加载驱动完毕");

String url="jdbc:mysql://localhost:3306/studentmanager";

String username="root";

String password="root";

String sql1="select * from images";

Connection conn=DriverManager.getConnection(url,username,password);

//创建一个 Statement 对象来将 SQL 语句发送到数据库。

PreparedStatement pst=conn.prepareStatement(sql1);

ResultSet rs=pst.executeQuery();

rs.next();

//从ResultSet中得到Blob的对象

Blob b=rs.getBlob("img");

//通过Blob对象的getBinaryStream得到字节流

InputStream fis= b.getBinaryStream();

//构建字节流的缓存BufferedInputStream的对象

BufferedInputStream bis=new BufferedInputStream(fis);

//准备一个FileOutputStream输出流对象

FileOutputStream fos =new FileOutputStream("d://2.jpg");

//准备一个字节数组,以备缓存读对象BufferedInputStream,每次读这些字节长度

byte[] be=new byte[1024];

//每读1024个字节就向FileOutputStream写1024个字节,直到写完。

while((bis.read(be))!=-1){

fos.write(be);

}

fos.flush();

fos.close();

fis.close();

bis.close();

} catch (Exception ex) {

ex.printStackTrace();

}

}

public void write(){

try {

Class.forName("com.mysql.jdbc.Driver");

//System.out.print("加载驱动完毕");

String url="jdbc:mysql://localhost:3306/studentmanager";

String username="root";

String password="root";

String sql1="insert into images values (?)";

Connection conn=DriverManager.getConnection(url,username,password);

//创建一个 Statement 对象来将 SQL 语句发送到数据库。

PreparedStatement pst=conn.prepareStatement(sql1);

File file=new File("e://1.jpg");

int len=(int)file.length();

FileInputStream fis=new FileInputStream(file);

pst.setBinaryStream(1,fis,len);

int count=pst.executeUpdate();

if(count>0){

System.out.println("执行成功");

}else{

System.out.println("执行未返回任何影响行数");

}

} catch (Exception ex) {

ex.printStackTrace();

}

其实就是以二进制形式存储在数据库了,此方法不推荐了因为数据多了不方便处理了并且数据库会很大查询也比较慢了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值