用JDBC访问二进制类型的数据
public class BlobTest {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
// create();
read();
}
// 从数据库读取二进制类型的数据
static void read() throws SQLException, IOException, ClassNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");
// 3.创建语句
ps = conn.prepareStatement("select big_bit from blob_test");
// 4.执行语句
rs = ps.executeQuery();
// 5.处理结果
while (rs.next()) {
Blob blob = rs.getBlob(1);
InputStream in = blob.getBinaryStream();
File file = new File("IMG_0002_bak.jpg");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buff = new byte[1024];
for (int i = 0; (i = in.read(buff)) > 0;) {
out.write(buff, 0, i);
}
out.close();
in.close();
}
} finally {
if (rs != null) rs.close(); rs = null;
if (ps != null) ps.close(); ps = null;
if (conn != null) conn.close(); conn = null;
}
}
// 把二进制类型的数据(这里是一张图片)存入数据库
static void create() throws SQLException, IOException, ClassNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");
// 3.创建语句
String sql = "insert into blob_test(big_bit) values (?)";
ps = conn.prepareStatement(sql);
File file = new File("IMG_0002.jpg");
InputStream in = new BufferedInputStream(new FileInputStream(file));
ps.setBinaryStream(1, in, (int) file.length());
// 4.执行语句
int i = ps.executeUpdate();
in.close();
System.out.println("i=" + i);
} finally {
if (rs != null) rs.close(); rs = null;
if (ps != null) ps.close(); ps = null;
if (conn != null) conn.close(); conn = null;
}
}
}