实现向MYSQL数据库中存储或提取图片文件
一些情况下,需要向数据库中存储一些2进制文件,比如图片文件等,这时候,向数据库存储数据不同于普通的字符串存储,我们需要对这个2进制文件使用JAVA处理2进制流的API进行处理,然后再进行存储。我们需要进行以下步骤来实现:
向数据库中存储文件的时候,一样使用标准SQL语句,如: insert into database (column1, column2,..) values(v1,v2,…);注意的是,要在建立存放2进制文件的TABLE时,存放的字段要使用BLOB类型,而不是普通的VARCHAR等。BLOB是专门存储2进制文件的类型,他还有大小之分,比如mediablob,logblob等,以存储大小不同的2进制文件,一般的图形文件使用mediablob足以了。
1 见以下代码实现向MYSQL中储存图片文件:
…………………………
private final String insertquery = "insert into employeephoto (Employee_ID,Binary_Photo,LastMod,Created) values (?,?, NOW(), NOW())";
java 代码
- public void doInsertStaffPic(String loginname,String source_URL) {
-
- Connection conn = null;
-
- PreparedStatement pre = null;
- try {
-
-
- conn = DBProcess.getConnection();
-
-
- Image image = new ImageIcon(source_URL).getImage();
-
- BufferedImage bImage = new BufferedImage(image.getWidth(null),
-
- image.getHeight(null), BufferedImage.TYPE_INT_RGB);
-
- Graphics bg = bImage.getGraphics();
-
- bg.drawImage(image, 0, 0, null);
-
- bg.dispose();
-
-
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
-
- ImageIO.write(bImage, "jpg", out);
-
- byte[] buf = out.toByteArray();
-
-
- ByteArrayInputStream inStream = new ByteArrayInputStream(buf);
- pre = conn.prepareStatement(insertstaffpicquery);
- pre.setString(1, loginname);
- pre.setBinaryStream(2, inStream, inStream.available());
-
-
- pre.executeUpdate();
- } catch (Exception exc) {
- exc.printStackTrace();
- }
- finally {
- try {
- pre.close();
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
2 下代码实现从MYSQL中获取图片文件并写入本地文件系统:
…………………………
private final String writeoutquery = "insert into employeephoto (Employee_ID,Binary_Photo,LastMod,Created) values (?,?, NOW(), NOW())";
java 代码
-
-
- public void doGetAndShowStaffPic(String loginname, String dir) {
- FileOutputStream output = null;
-
- InputStream input = null;
- Connection conn = null;
- ResultSet rs = null;
- PreparedStatement pre = null;
- try {
-
- conn = DBProcess.getConnection();
- pre = conn.prepareStatement(writeoutquery);
- pre.setString(1, loginname);
- rs = pre.executeQuery();
- if (rs.next()) {
-
-
- Blob image = rs.getBlob("Binary_Photo");
-
-
- Input = image.getBinaryStream();
- try {
-
-
- output = new FileOutputStream(dir);
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
-
- byte[] rb = new byte[1024000];
- int ch = 0;
-
- try {
-
-
- while ((ch = input.read(rb)) != -1) {
- output.write(rb, 0, ch);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- output.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- finally {
- try {
- rs.close();
- pre.close();
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
来源于javaResearch,作者 Jegg