摘要:本教程向您展示如何使用 JDBC API 写入和读取 MySQL BLOB 数据。
我们将使用mysqljdbc 示例数据库中的candidates
表。为了演示起见,我们将在candidates
表中再添加一列名为resume
的列。该列的数据类型为MEDIUMBLOB
,最多可容纳 16MB。
以下ALTER TABLE 语句将简历列添加到candidates
表中。
ALTER TABLE candidates
ADD COLUMN resume LONGBLOB NULL AFTER email;
Code language: SQL (Structured Query Language) (sql)
我们将使用 PDF 格式的示例简历,稍后将此文件加载到candidates
表的resume
列中。您可以通过以下链接下载示例 PDF 文件进行练习:
将BLOB数据写入MySQL数据库
将BLOB数据写入MySQL数据库的步骤如下:
首先,通过创建新的Connection
对象来打开与数据库的新连接。
Connection conn = DriverManager.getConnection(url,username,password);
Code language: Java (java)
然后,构造一个UPDATE 语句并从Connection
对象创建一个PreparedStatement
。
String updateSQL = "UPDATE candidates "
+ "SET resume = ? "
+ "WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(updateSQL);
Code language: Java (java)
接下来,使用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);
Code language: Java (java)
之后,调用PreparedStatement
对象的executeUpdate()
方法。
pstmt.executeUpdate();
Code language: Java (java)
最后,通过调用close()
方法关闭PreparedStatement
和Connection
对象。
为了简化Connection
创建过程,我们使用在上一篇教程中开发的MySQLJDBCUtil
类来打开新连接。将BLOB数据写入MySQL数据库的完整示例如下:
package org.mysqltutorial;
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 mysqltutorial.org
*/
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");
}
}
Code language: Java (java)
让我们运行该程序。
现在我们检查candidates
表中 id 为 122 的候选人。
SELECT * FROM candidates WHERE id = 122;
Code language: SQL (Structured Query Language) (sql)
正如您所看到的,我们在candidates
表的简历列中更新了 id 为 122 的记录的 BLOB 数据。
从 MySQL 数据库读取 BLOB 数据
从数据库读取BLOB数据的过程与写入BLOB的过程类似,除了我们将BLOB数据写入文件的部分。
首先,打开与数据库的新连接。
Connection conn = MySQLJDBCUtil.getConnection(dbURL,username,password);
Code language: Java (java)
然后,构造一个SELECT 语句并从Connection
对象创建一个PreparedStatement
。
String selectSQL = "SELECT resume FROM candidates WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(selectSQL);
Code language: Java (java)
接下来,设置参数并执行查询:
pstmt.setInt(1, candidateId);
ResultSet rs = pstmt.executeQuery();
Code language: Java (java)
之后,从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);
}
}
Code language: Java (java)
最后,调用PreparedStatment
和Connection
对象的close()
方法。如果您使用 try-with-resources 语句,则不必显式执行。
以下示例说明如何从 MySQL 数据库读取 BLOB 数据。
package org.mysqltutorial;
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");
}
}
Code language: Java (java)
运行程序后,浏览项目文件夹,您将看到创建了一个名为johndoe_resume_from_db.pdf
的新文件。
在本教程中,我们向您展示了如何通过 JDBC 使用 MySQL BLOB 数据。