MySQL数据库写入图片并读取图片显示到JLabel上的详解

来源:互联网 发布:k近邻算法流程图 编辑:程序博客网 时间:2024/05/01 23:44

相较于Oracle,MySQL作为一个轻量级的开源的数据库,可谓是大大简化了我们的操作。这次我就来写一个关于数据库存入图片,获取图片的例子吧,也为了今后的复习使用。(我们一般采取存入路径的方式,而不是直接存储字节的方式,毕竟读取的时候还要通过字节读取,并做一些转换,这真的是太麻烦了,但是咧,这次就来个麻烦的吧,咱们用字节的方式)
首先我们需要在MySQL数据库中创建好我们所需要的表我已经创建好了,如图所示
,下面就是正式的编码了,我们需要一个数据库专用类,用于对数据库的一些操作,我称之为DBUtils

package DBUtils;import java.sql.DriverManager;import java.sql.SQLException;import com.mysql.jdbc.*;public class ConnectionToMySQL {    private String DRIVER,name,password;    public ConnectionToMySQL() {        // TODO Auto-generated constructor stub    }    public static void main(String []args){        getConnection();    }    public static Connection getConnection(){        Connection conn=null;        try {            String DRIVER="com.mysql.jdbc.Driver";            String url="jdbc:mysql://localhost:3306/tiger";            Class.forName(DRIVER);            conn=(Connection) DriverManager.getConnection(url, "root", "mysql");            System.out.println("Succeed in Connect to your Database!");        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return conn;    }}

很明显,接下来就是往数据库存入我们的图片了,代码如下,

import java.sql.SQLException;import DBUtils.ConnectionToMySQL;import com.mysql.jdbc.PreparedStatement;public class SaveImage {    public SaveImage() {        // TODO Auto-generated constructor stub    }    public static String insertImage(){        String flag="";        String sql="insert into tiger.ImageTable values(?,?)";        try {            PreparedStatement ps=(PreparedStatement) ConnectionToMySQL.getConnection()                    .prepareStatement(sql);            ps.setString(1, "mySelf");            ps.setString(2, "image1");            ps.execute();            if(ps.execute()){                flag="成功插入数据!!!";            }else{                flag="抱歉,未能 成功插入数据!!!";            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return flag;    }}

再然后就是读取图片,或者写入到本地文件下(请注明路径和文件名称,因为等会我们要使用哟),代码如下:

package image;import java.io.FileOutputStream;import java.io.InputStream;import java.sql.ResultSet;import java.sql.SQLException;import DBUtils.ConnectionToMySQL;import com.mysql.jdbc.Blob;import com.mysql.jdbc.PreparedStatement;public class GetImage {    public GetImage() {        // TODO Auto-generated constructor stub    }    /**     * 这二个方法仅仅是测试我们的数据库中到底有什么值,并没有什么大的用处     * @return     */    public static String getAndRead(){        String flag="";        String sql="select * from ImageTable";        try{            PreparedStatement ps=(PreparedStatement) ConnectionToMySQL.getConnection()                .prepareStatement(sql);            ResultSet rs=ps.executeQuery();            while(rs.next()){                System.out.print(rs.getString("name")+"\t");                System.out.println(rs.getString("image"));            }        }catch(SQLException e){            e.printStackTrace();        }catch(Exception ee){            ee.printStackTrace();        }        return flag;    }    /**     * 读取数据库中的blob类型的图片文件,并存储到本地     * @throws SQLException     */    public static void SetBlobToFile() throws SQLException{        InputStream bb=null;        String sql="select image from ImageTable where name='mySelf';";        try{            PreparedStatement ps=(PreparedStatement) ConnectionToMySQL.getConnection()                .prepareStatement(sql);            ResultSet rs=ps.executeQuery();            rs.next();            bb=rs.getBinaryStream("image");            FileOutputStream os = new FileOutputStream("F:\\target"+".jpg");            byte[] buff = new byte[1024];            os.write(buff);            rs=null;            System.out.println("图片文件写入本地成功!");        }catch(SQLException e){            e.printStackTrace();        }catch(Exception ee){            ee.printStackTrace();        }    }}

下面开始进行整体的存储吧:

package image;import java.sql.SQLException;public class Test {    public Test() {        // TODO Auto-generated constructor stub    }    public static void main(String[] args) throws SQLException {        // TODO Auto-generated method stub        System.out.println("程序开始!");        SaveImage.insertImage();        GetImage.getAndRead();        GetImage.SetBlobToFile();        System.out.println("程序结束!");    }}

运行结果:
Succeed in Connect to your Database!
Doge doge.gif
mySelf image1.jpg
Succeed in Connect to your Database!
图片文件写入本地成功!
程序结束!

好了,完事具备,就差对我们的成果进行检验了,下面请看一个Demo,就是使用我们从数据库中获取到的图片的使用案例,代码如下:

package image;import java.awt.BorderLayout;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;public class PictureInstance extends JFrame {    private JLabel label;    public static void main(String[] args) {        // TODO Auto-generated method stub        new PictureInstance();    }    public PictureInstance(){        label=new JLabel();        this.setSize(500,400);        this.setVisible(true);        this.setLocationRelativeTo(null);        this.setDefaultCloseOperation(EXIT_ON_CLOSE);        this.add(label,BorderLayout.CENTER);        label.setIcon(new ImageIcon("F:\\target.jpg"));    }}

下面就是运行的结果了,
从数据库中读取到的图片的展示
好了,大概就是这样了。虽然这种方式会导致数据的部分丢失,而且方式繁琐冗杂。个人建议使用路径的方式存储以及读取图片更为合理,且更为方便高效。

0 0
原创粉丝点击