Java SQL Blob
接口Blob是java.sql软件包的一部分。
Blob是SQL blob数据类型的Java表示形式。
Blob用于保存和检索数据库中的二进制数据。
ResultSet,PreparedStatement和CallableStatement支持Blob。
Java SQL Blob的方法
long length():此方法返回Blob对象的大小。
byte [] getBytes(long pos,int length):此方法从指定位置开始,使用指定的长度返回blob对象的字节数组。
InputStream getBinaryStream():此方法返回当前Blob对象的InputStream。
InputStream getBinaryStream(long pos,long length):此方法返回指定长度并从给定位置开始的当前Blob Object的InputStream。
void free():此方法释放blob对象并释放Blob对象使用的资源。
OutputStream setBinaryStream(long pos):此方法返回OutputStream,可用于设置Blob数据。
int setBytes(long pos,byte [] bytes):此方法从指定位置开始将指定的字节数组写入当前Blob对象,并返回写入的字节数。
void truncate(long len):此方法使用指定的长度截断Blob对象的值。
Java SQL Blob示例
我们将看到Blob的两个不同示例。
我们将使用MySQL数据库来演示Blob的用法。
在Java项目的pom.xml中使用以下maven依赖项。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency>
在第一个示例中,我们将文件的内容保存在DB中,在第二个示例中,我们将使用序列化将自定义Java类的对象保存到DB中。
1.在数据库中保存并获取文件
使用以下数据库脚本创建数据库和表。
create database blobdb; use blobdb; create table tblfile( fileid int, filevalue blob );
让我们看下面的示例程序,将数据保存到Blob列中。
package com.theitroad.example;
/**
* Java example program to read and write blob object using file
*
* @author hyman
*
*/
import java.io.*;
import java.sql.*;
public class BlobFileDemo {
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
File file = new File("/home/demo/blob.txt");
//Initialize the file object using text file location as above
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/blobdb?useSSL=false", "root",
"root");
writeObject(file, connection);
readObject(connection);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
}
public static void writeObject(File file, Connection connection) throws Exception {
PreparedStatement pStmt = null;
ByteArrayOutputStream bAout = new ByteArrayOutputStream();
try {
pStmt = connection.prepareStatement("insert into tblfile(fileid, filevalue) values(?, ?)");
pStmt.setInt(1, 1);
pStmt.setBlob(2, new FileInputStream(file));
//Set FileInputStream object as blob
pStmt.execute();
} finally {
bAout.close();
pStmt.close();
}
}
public static void readObject(Connection connection) throws Exception {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("select fileid,filevalue from tblfile where fileid=1");
if (resultSet.next()) {
int fildId = resultSet.getInt("fileid");
Blob blob = resultSet.getBlob("filevalue");
//getBlob method of ResultSet is used to get Blob from database.
//Now we can use Blob to save data to file or transfer data to other place.
System.out.println("FileId:" + fildId);
System.out.println("Blob:" + blob);
int length = (int) blob.length();
//length() method will return size of Blob Object.
System.out.println("length:" + length);
System.out.println(new String(blob.getBytes(1L, length)));
//I have used text file so that It can be displayed on console.
}
} finally {
statement.close();
}
}
}
输出:
FileId:1 Blob:com.mysql.jdbc.Blob@41906a77 length:40 This is an example file for blob object
数据库值:
值将取决于您使用的文件的内容。
MariaDB [blobdb]> select * from tblfile where fileid=1; +--------+------------------------------------------+ | fileid | filevalue | +--------+------------------------------------------+ | 1 | This is an example file for blob object | +--------+------------------------------------------+
2.在数据库中保存并获取自定义Java对象
使用下面的数据库脚本创建表。
create table tblstudent( studentObj blob );
让我们看下面的示例程序。
package com.theitroad.example;
/**
* Java example program to read and write blob object
*
* @author hyman
*
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class BlobDemo {
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
Student student = new Student("hyman", "[email protected]");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/blobdb?useSSL=false", "root",
"root");
writeObject(student, connection);
Student dbStudent = readObject(connection);
System.out.println(dbStudent);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
}
public static void writeObject(Student student, Connection connection) throws Exception {
PreparedStatement pStmt = null;
ByteArrayOutputStream bAout = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(bAout);
try {
objOut.writeObject(student);
objOut.flush();
pStmt = connection.prepareStatement("insert into tblstudent(studentObj) values(?)");
pStmt.setBlob(1, new ByteArrayInputStream(bAout.toByteArray()));
pStmt.execute();
} finally {
objOut.close();
bAout.close();
pStmt.close();
}
}
public static Student readObject(Connection connection) throws Exception {
Student student = null;
ObjectInputStream objIn = null;
ByteArrayInputStream bIn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("select studentObj from tblstudent");
if (resultSet.next()) {
Blob studBlob = resultSet.getBlob("studentObj");
bIn = new ByteArrayInputStream(studBlob.getBytes(1, (int) studBlob.length()));
objIn = new ObjectInputStream(bIn);
student = (Student) objIn.readObject();
}
} finally {
objIn.close();
bIn.close();
statement.close();
}
return student;
}
}
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String email;
public Student(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [name=" + name + ", email=" + email + "]";
}
}
注意:Class Student实现了Serializable接口。
ObjectOutputStream和ObjectInputStream用于将Student对象转换为二进制形式,反之亦然。
3.在数据库中保存并获取图像文件对象
package com.theitroad.example;
/**
* Java example program to read and write blob object using image file
*
* @author hyman
*
*/
import java.io.*;
import java.sql.*;
import java.util.Base64;
public class BlobImageDemo {
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
File file = new File("/home/demo/img.jpg");
//Initialize the file object using image file location as above
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/blobdb?useSSL=false", "root",
"root");
writeObject(file, connection);
readObject(connection);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
}
public static void writeObject(File file, Connection connection) throws Exception {
PreparedStatement pStmt = null;
ByteArrayOutputStream bAout = new ByteArrayOutputStream();
try {
pStmt = connection.prepareStatement("insert into tblfile(fileid, filevalue) values(?, ?)");
pStmt.setInt(1, 1);
pStmt.setBlob(2, new FileInputStream(file));
//Set FileInputStream object as blob
pStmt.execute();
} finally {
bAout.close();
pStmt.close();
}
}
public static void readObject(Connection connection) throws Exception {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("select fileid,filevalue from tblfile where fileid=1");
if (resultSet.next()) {
int fildId = resultSet.getInt("fileid");
Blob blob = resultSet.getBlob("filevalue");
//getBlob method of ResultSet is used to get Blob from database.
//Now we can use Blob to save data to file or transfer data to other place.
System.out.println("FileId:" + fildId);
System.out.println("Blob:" + blob);
int length = (int) blob.length();
//length() method will return size of Blob Object.
System.out.println("length:" + length);
String base64Image = Base64.getEncoder().encodeToString(blob.getBytes(1L, length));
//Encode image byte array into base64
//System.out.println("Base64 Image data: "+base64Image);
//Remove above comments to print image data
}
} finally {
statement.close();
}
}
}
输出:
FileId:1 Blob:com.mysql.jdbc.Blob@4b85612c length:11397

