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

         }

        

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM