今天项目要提供一个版本给现场的同事做测试,并且初始化数据当中有blob数据,所以为了解决这个问题在网上找了好些资料东凑西凑终于把这个给弄好了,代码大概就是这样:
//将数据库中的blob数据存储为txt文件
public static void export(){String url = Global.getConfig("db.rsk.url");//数据连接
String name = Global.getConfig("db.rsk.driver");//数据库驱动
String user = Global.getConfig("db.rsk.username");//用户名
String password = Global.getConfig("db.rsk.password"); //密码
Connection conn = null; //链接对象
PreparedStatement pst = null; //处理对象
try {
Class.forName(name);//指定连接类型
conn = DriverManager.getConnection(url, user, password);//获取连接
pst = conn.prepareStatement("select * from act_ge_bytearray");//准备执行语句
ResultSet ret = pst.executeQuery();//执行语句,得到结果集
int i = 0;//因为有多行数据,所以用个变量来改变文件的名字
while (ret.next()) {
String uid = ret.getString(1); //获取字段值
String ufname = ret.getString(2);
String ulname = ret.getString(3);
String udate = ret.getString(4);
Blob blob = ret.getBlob(5); //获取blob数据
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();//二进制输出流
InputStream inputStream = blob.getBinaryStream();//获取blob的输入流
byte[] buff = new byte[1024]; //存放循环读取的临时数据
int rc = 0;
while ((rc = inputStream.read(buff, 0, 100)) > 0) {//循环读取流
swapStream.write(buff, 0, rc);
}
byte[] fStreamByte = swapStream.toByteArray(); //in_b为转换之后的结果
OutputStream os = new FileOutputStream(new File("F:\\"+i+"a.txt"));//创建文件输出流
os.write(fStreamByte);//写入文件
os.close();
String genareted = ret.getString(6);
i++;
}//显示数据
ret.close();
conn.close();
pst.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//将文件转成blob后插入数据库
public static void imports(){
String [] ids = {"37599fdd70ec4714b699030a3dcbd0af","316e5556ca4f4beaa86ab9e76fe5a54c","13ff24a5f83344c19056e1e5ae77ec11","a7ac28afcf504d70aadd7f071ee0a985"};String url = Global.getConfig("db.rsk.url");//数据连接
String name = Global.getConfig("db.rsk.driver");//数据库驱动
String user = Global.getConfig("db.rsk.username");//用户名
String password = Global.getConfig("db.rsk.password"); //密码
Connection conn = null;
PreparedStatement pst = null;
try {
Class.forName(name);//指定连接类型
conn = DriverManager.getConnection(url, user, password);//获取连接
for(int i = 0;i < 4;i++){
pst = conn.prepareStatement("select * from act_ge_bytearray where id_ = '37599fdd70ec4714b699030a3dcbd0af' for update");//准备执行语句
ResultSet ret = pst.executeQuery();//执行语句,得到结果集
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File("F:\\"+i+"a.txt")));
BufferedOutputStream bos = null;
oracle.sql.BLOB image = null;
while (ret.next()) {
image = (oracle.sql.BLOB)ret.getBlob("bytes_"); //获取blob数据
bos = new BufferedOutputStream(image.getBinaryOutputStream());
int c;
while ((c = fis.read()) != -1) { // 将实际文件中的内容以二进制的形式来输出到blob对象对应的输出流中
bos.write(c);
}
bos.close();
fis.close();
}
String writeSql = "update act_test set bytes_ = ? where id_ = ?"; //将blob数据插入到数据库中
PreparedStatement ps = conn.prepareStatement(writeSql);
ps.setBlob(1, image);
ps.setString(2, ids[i]);
ResultSet rs = ps.executeQuery();
rs.close();
}
conn.close();
pst.close();
}catch(Exception e) {
e.printStackTrace();
}
}