以Mysql数据库为例, 完成图片的简单存储, 查询操作来说明Blob的应用
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
public class BlobTest extends JApplet {
public static final long serialVersionUID = 1l;
/**
* Mysql驱动类
*/
private static final String CONN_DRIVER = "org.gjt.mm.mysql.Driver";
/**
* 数据库连接URL
*/
private static final String CONN_URL = "jdbc:mysql://localhost:3306/dcc";
/**
* 数据库用户
*/
private static final String CONN_USER = "root";
/**
* 图片存放位置
*/
private static final String FILE_NAME = "C://Winter.jpg";
/**
* Bolb对象
*/
static Blob blob = null;
/**
* 初始化
*/
public void init() {
insert();
try {
blob = query();
} catch (Exception e) {
e.printStackTrace();
}
ImageIcon icon = null;
try {
icon = new ImageIcon(blob.getBytes(1, (int) blob.length()));
} catch (SQLException e) {
e.printStackTrace();
}
JLabel lable = new JLabel(icon);
getContentPane().add(lable);
setVisible(true);
}
/**
* 执行数据库insert操作
*
* @return boolean
*/
private boolean insert() {
boolean flag = false;
PreparedStatement stmt = null;
String sql = "insert into picture values(?,?)";
File file = new File(FILE_NAME);
FileInputStream in = null;
Connection conn = null;
try {
conn = getConnection();
in = new FileInputStream(file);
stmt = conn.prepareStatement(sql);
stmt.setString(1, "test");
stmt.setBinaryStream(2, in, (int) file.length());
if (stmt != null) {
stmt.executeUpdate();
flag = true;
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 查询图片对象
*
* @return
* @throws Exception
*/
private Blob query() throws Exception {
PreparedStatement stmt = null;
ResultSet rs = null;
String quer_sql = "select pic from picture where id=?;";
try {
Connection conn = getConnection();
stmt = conn.prepareStatement(quer_sql);
stmt.setString(1, "test");
if (stmt != null) {
rs = stmt.executeQuery();
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.next();
return rs.getBlob("pic");
}
/**
* 获取数据库连接
*
* @return
*/
private Connection getConnection() {
Connection conn = null;
try {
Class.forName(CONN_DRIVER);
conn = DriverManager.getConnection(CONN_URL, CONN_USER, "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.println( "数据库出现异常" + e.getMessage() );
e.printStackTrace();
}
return conn;
}
}