前言
kettle文件实现!!!
需要将数据库中的blob字段,批量生成文件并保存在本地,并将文件路径输出
可能是因为版本的问题(我猜的)导致不能直接读取出blob类型字段的完整内容
这是kettle 中java 组件获取上一步组件传入数据的方式,不能直接获取
-----
String id = get(Fields.In, "blobData").getString(r);
数据传入
由前面的组件传入id(我是需要输出指定数据的文件才传入id),然后在java组件里去做数据库里查询,就可以获取到这个字段的值 ,然后在这里做导出文件
文件导出代码
下面是我java 组件的完整代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
//文件输出路径
private static String path="D:/getBlobFlie/";
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
//由上一步传入,数据主键id(你如果需要输出全表数据的blob文件),下面sql的地方自己看着写
String id = get(Fields.In, "id").getString(r);
Connection connection = null;
Statement stmt = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//数据库连接信息
String SDdriver = "";
String SDurl = "";
String SDuser = "";
String SDpassword = "";
Class.forName(SDdriver);
connection = DriverManager.getConnection(SDurl, SDuser, SDpassword);
} catch (Exception e) {
e.printStackTrace();
}
//自己改sql
String sql ="SELECT clobData from ? where id="+id;
try {
stmt = connection.createStatement();
resultSet = stmt.executeQuery(sql);
while (resultSet.next()) {
Blob blob = resultSet.getBlob("clobData");
long length = resultSet.getBlob("clobData").length();
byte[] stream = resultSet.getBlob("clobData").getBytes(1, (int) length);
String personaldata = resultSet.getString("clobData");
String output = output(stream,"文件名","文件类型"");
//文件生成错误了,看你想怎么处理咯
if("ERROR".equals(output)){
return true;
}
//最后输出文件路径
get(Fields.Out,"path").setValue(r,output);
putRow(data.outputRowMeta, r);
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(connection, preparedStatement,resultSet);
}
return true;
}
public static String output(byte[] input,String filename,String type) throws Exception {
String filePath="";
if (input != null && input.length > 0) {
filePath=path + filename + "." + type;
try {
File w2 = new File(filePath);//可以是jpg,png,gif格式
FileOutputStream imageOutput = new FileOutputStream(w2);//打开输入流
imageOutput.write(input, 0, input.length);//将byte写入硬盘
imageOutput.close();
}catch (Exception e) {
return "ERROR";
}
}
return filePath;
}
public static void closeAll(Connection connection, PreparedStatement preparedStatement,ResultSet resultSet) {
try {
if(resultSet!=null) {
resultSet.close();
}
if (preparedStatement!=null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}