zoukankan      html  css  js  c++  java
  • 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();

             }

            

    }

  • 相关阅读:
    C# 两个窗体中相互切换的方法
    Linq对DataTable数据的分组统计
    如何让窗体大小随着控件的大小变化而变化
    两张表解决用户自定义数据库之思路
    picturebox显示用字符串代表图片名称的(已导入资源的)图片
    如何将access高版本数据库保存为低版本的?
    Microsoft.Jet.OLEDB.4.0和Microsoft.ACE.OLEDB.12.0的区别
    条件编译解决AutoCAD多版本问题
    一个爬取股票信息的爬虫程序
    Python爬虫抓取东方财富网股票数据并实现MySQL数据库存储
  • 原文地址:https://www.cnblogs.com/jway1101/p/5815658.html
Copyright © 2011-2022 走看看