mysql Blob存取的一个简单例子

本文介绍如何在Java中通过JDBC连接MySQL数据库,并实现Blob类型数据的存取操作,包括将文件保存到数据库及从数据库读取文件并写入本地。

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

一、得到mysql的连接

这里封装成一个方法,方便后面使用。

public Connection getConnection() throws Exception{

 

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

         String user = "root";

         String password = "root";

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

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

         return conn;

 

}

 

二、将数据存入数据库

/**

 *

 * @param file  需要传入数据库的文件

 * @throws Exception

 */

public void save(File file) throws Exception{

         Connection conn = getConnection();

         String sql = "insert into tb_blob (name,myfile) values(?,?)";

         PreparedStatement prest = conn.prepareStatement(sql);

        

         String filename=file.getName();

         prest.setString(1, filename);//根据文件名称来保存

        

         FileInputStream fis = new FileInputStream(file);

         prest.setBlob(2, fis,file.length());//第二个参数需要一个InputStream

        

         prest.execute();   //执行

}

三、将数据取出,同时写入文件。

 

/**

 *

 * @param filename  列的值,同时是文件名

 * @throws Exception

 */

public void getMp3(String filename) throws Exception{

         Connection conn = getConnection();

         String sql = "select * from tb_blob where name= ?";

         PreparedStatement prest = conn.prepareStatement(sql);

         prest.setString(1, filename);

        

         ResultSet rs = prest.executeQuery();

         while(rs.next()){

                   Blob  bl = rs.getBlob("myfile");//数据保存在"myfile",这里则是取出这里保存的数据。

                   InputStream is = bl.getBinaryStream();  //查看blob,可以通过流的形式取出来。

                  

                   BufferedInputStream buffis = new BufferedInputStream(is);

                   //保存到buffout,就工程目录下的filename的文件

                   BufferedOutputStream buffout = new BufferedOutputStream(new FileOutputStream(filename));

                  

                   byte[] buf= new byte[1024];

                   int len = buffis.read(buf, 0, 1024);

                   while(len>0){

                            buffout.write(buf);

                            len=buffis.read(buf, 0, 1024);

                   }

                   buffout.flush();

                   buffout.close();

                   buffis.close();

         }

        

}

 

转载于:https://www.cnblogs.com/jway1101/p/5815658.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值