以下代码示例,可用于通过JDBC连接Oracle数据库,并从A_TEST表中获取BLOB类型字段并将其下载到C:\test目录下:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
public class OracleBlobDownloader {
public static void main(String[] args) {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@//localhost:1521/orcl"; // 根据实际情况修改数据库连接URL
String username = "your_username"; // 根据实际情况修改用户名
String password = "your_password"; // 根据实际情况修改密码
String tableName = "A_TEST"; // 表名
String blobColumnName = "BLOB_COLUMN"; // BLOB类型字段名
String savePath = "C:\\test\\blob_file"; // 下载保存路径
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT " + blobColumnName + " FROM " + tableName);
if (resultSet.next()) {
Blob blob = resultSet.getBlob(blobColumnName);
InputStream inputStream = blob.getBinaryStream();
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
System.out.println("BLOB字段下载成功!");
} else {
System.out.println("没有找到符合条件的记录。");
}
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Oracle驱动未找到:" + e.getMessage());
} catch (SQLException e) {
System.out.println("数据库连接错误:" + e.getMessage());
} catch (IOException e) {
System.out.println("文件下载失败:" + e.getMessage());
}
}
}
请确保以下几点:
- 根据实际情况修改数据库连接URL、用户名和密码。
- 根据实际情况,将A_TEST替换为您要查询的表名,将BLOB_COLUMN替换为包含BLOB类型数据的字段名。
- 请注意设置正确的保存路径。在上述示例代码中,文件会保存在C:\test\blob_file。
运行代码后,它将通过JDBC连接到指定的Oracle数据库,并从A_TEST表中获取BLOB字段的内容并保存到指定的路径下。如果成功下载BLOB字段,将打印出"BLOB字段下载成功!“。如果未找到符合条件的记录,将打印出"没有找到符合条件的记录。”。