mysql Blob存取的一个简单例子

一、得到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();

         }

        

}

 

posted @ 2016-08-28 18:57  jway0101  阅读(19405)  评论(0编辑  收藏  举报