使用JDBC编写和读取MySQL BLOB数据
简介:本教程向您展示如何使用JDBC API写入和读取MySQL BLOB数据。
我们将使用mysqljdbc示例数据库中的候选人表。
为了演示起见,我们将在候选人表中再添加一个名为" resume"的列。
该列的数据类型将为MEDIUMBLOB,最多可容纳16MB。
以下ALTER TABLE语句将resume列添加到候选人表。
ALTER TABLE candidates ADD COLUMN resume LONGBLOB NULL AFTER email;
我们将使用PDF格式的示例简历,并将此文件稍后加载到候选人表的简历栏中。
将BLOB数据写入MySQL数据库
将BLOB数据写入MySQL数据库的步骤如下:
首先,通过创建新的Connection对象来打开与数据库的新连接。
Connection conn = DriverManager.getConnection(url,username,password);
然后,构造一个UPDATE语句并从Connection对象创建一个PreparedStatement。
String updateSQL = "UPDATE candidates "
+ "SET resume = ? "
+ "WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(updateSQL);
接下来,使用FileInputStream从示例简历文件中读取数据,并调用setBinaryStream()方法来设置PreparedStatement的参数。
// read the file File file = new File(filename); FileInputStream input = new FileInputStream(file); // set parameters pstmt.setBinaryStream(1, input); pstmt.setInt(2, candidateId);
之后,调用PreparedStatement对象的executeUpdate()方法。
pstmt.executeUpdate();
最后,通过调用close()方法关闭PreparedStatement和Connection对象。
为了简化Connection的创建过程,我们使用在上一教程中开发的MySQLJDBCUtil类来打开新的连接。
将BLOB数据写入MySQL数据库的完整示例如下:
package org.theitroad;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
*
* @author theitroad.local
*/
public class Main {
/**
* Update resume for a specific candidate
*
* @param candidateId
* @param filename
*/
public static void writeBlob(int candidateId, String filename) {
// update sql
String updateSQL = "UPDATE candidates "
+ "SET resume = ? "
+ "WHERE id=?";
try (Connection conn = MySQLJDBCUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
// read the file
File file = new File(filename);
FileInputStream input = new FileInputStream(file);
// set parameters
pstmt.setBinaryStream(1, input);
pstmt.setInt(2, candidateId);
// store the resume file in database
System.out.println("Reading file " + file.getAbsolutePath());
System.out.println("Store file in the database.");
pstmt.executeUpdate();
} catch (SQLException | FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
writeBlob(122, "johndoe_resume.pdf");
}
}
让我们运行程序。
现在,我们检查ID为122的候选人的候选人表。
SELECT * FROM candidates WHERE id = 122;
如您所见,我们在候选人表的恢复列中更新了BLOB数据,以记录ID为122的记录。
从MySQL数据库读取BLOB数据
从数据库读取BLOB数据的过程与写入BLOB的过程相似,除了将BLOB数据写入文件的部分。
首先,打开与数据库的新连接。
Connection conn = MySQLJDBCUtil.getConnection(dbURL,username,password);
然后,构造一个SELECT语句并从Connection对象创建一个PreparedStatement。
String selectSQL = "SELECT resume FROM candidates WHERE id=?"; PreparedStatement pstmt = conn.prepareStatement(selectSQL);
接下来,设置参数并执行查询:
pstmt.setInt(1, candidateId); ResultSet rs = pstmt.executeQuery();
之后,从ResultSet中获取BLOB数据并将其写入文件中:
File file = new File(filename);
FileOutputStream output = new FileOutputStream(file);
System.out.println("Writing to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("resume");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
最后,调用PreparedStatment和Connection对象的close()方法。
如果您使用try-with-resources语句,则不必显式地执行它。
以下示例说明了如何从MySQL数据库读取BLOB数据。
package org.theitroad;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Main.org
*/
public class Main {
/**
* Read resume of a candidate and write it into a file
*
* @param candidateId
* @param filename
*/
public static void readBlob(int candidateId, String filename) {
// update sql
String selectSQL = "SELECT resume FROM candidates WHERE id=?";
ResultSet rs = null;
try (Connection conn = MySQLJDBCUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(selectSQL);) {
// set parameter;
pstmt.setInt(1, candidateId);
rs = pstmt.executeQuery();
// write binary stream into file
File file = new File(filename);
FileOutputStream output = new FileOutputStream(file);
System.out.println("Writing to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("resume");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//
readBlob(122, "johndoe_resume_from_db.pdf");
}
}
运行程序之后,浏览项目文件夹,您将看到创建了一个名为johndoe_resume_from_db.pdf的新文件。
在本教程中,我们向您展示了如何使用JDBC的MySQL BLOB数据。

