要讀取Java中的Blob字段,可以使用java.sql.Blob接口提供的方法。下面是一個簡單的示例:
import java.io.FileOutputStream;import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
public class BlobReader {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT blob_column FROM my_table WHERE id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("blob_column");
InputStream inputStream = blob.getBinaryStream();
FileOutputStream outputStream = new FileOutputStream("output_file.txt");
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
conn.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
在上面的示例中,通過JDBC連接到數據庫,執行SELECT語句來獲取Blob字段。然后,通過Blob對象的getBinaryStream()方法獲取輸入流,然后將其寫入到文件輸出流中。
注意:在實際使用中,需要替換`url`、`username`、`password`、`sql`和輸出文件的路徑。此外,還需要適當處理異常和關閉連接等操作。