java数据库编程——Insert and Retrieve Images from MySql Table Using Java

来源:互联网 发布:2017年淘宝客市场规模 编辑:程序博客网 时间:2024/06/15 18:55
【0】README
0.1)本文翻译自 http://harmeetsingh13.blogspot.jp/2013/03/insert-and-retrieve-images-from-mysql.html

【1】正文如下:
段1)演示 从数据库表中插入和查询出图片。大多数情况下,图片数据都存储在数据库外部的一些文件夹下,而将其路径存储到数据库。但是在一些场景下,我们需要将图片以二进制数据格式存储到数据库。
Create Table in MySQL : CREATE TABLE `image` (  `id` varchar(45) DEFAULT NULL,  `size` int(11) DEFAULT NULL,  `image` longblob);

段2) 在mysql中,我们使用blob 类型存储这样类型的数据。它 只支持5kb 的图片数据容量,但这也取决于数据库提供商。 

【2】代码示例
2.1)向数据库插入图片
import java.sql.*;import java.io.*;public class InsertImagesMysql{public static void main(String[] args){System.out.println("Insert Image Example!");String driverName = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/";String dbName = "test";String userName = "root";String password = "root";Connection con = null;try{   Class.forName(driverName);   con = DriverManager.getConnection(url+dbName,userName,password);   Statement st = con.createStatement();   File imgfile = new File("pic.jpg");    FileInputStream fin = new FileInputStream(imgfile);    PreparedStatement pre =   con.prepareStatement("insert into Image values(?,?,?)");    pre.setString(1,"test");   pre.setInt(2,3);   pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());   pre.executeUpdate();   System.out.println("Successfully inserted the file into the database!");   pre.close();   con.close(); }catch (Exception e1){System.out.println(e1.getMessage());}}}

2.2)从数据库查询图片并保存到本地
import java.sql.*;import java.io.*;public class RetriveImagesMysql{public static void main(String[] args){System.out.println("Retrive Image Example!");String driverName = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/";String dbName = "test";String userName = "root";String password = "root";Connection con = null;try{Class.forName(driverName);con = DriverManager.getConnection(url+dbName,userName,password);Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery("select image from image");int i = 0;while (rs.next()) {InputStream in = rs.getBinaryStream(1);OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));i++;int c = 0;while ((c = in.read()) > -1) {f.write(c);}f.close();in.close();}}catch(Exception ex){System.out.println(ex.getMessage());}}}


0 0