这两天与小伙伴写了一个小程序,实现的功能如下:
首先将数据库的clob保存为本地的xml文件,然后对xml进行修改后上传至数据库
主要的难点如下:
1:clob文件的下载与上传,其中保存为本地的文件要求是UTF-8格式
2:xml文件中节点的修改
clob的上传与下载如下
?
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author GuoDi-CT DC
*
*/
public class ClobModify {
/**
*@param id 数据库中的ID
* 返回 保存文件的绝对路径
*/
public static String ClobToXml(int id) {
Connection conn = DB.getConn();
Statement stmt = DB.createStmt(conn);
String sql = "select * from BD_PROCESS_DEF_VER where ID =" + id;
ResultSet rs = DB.getRs(stmt, sql);
String xmlFile = null;
try {
if (rs.next()) {
int fjbh = rs.getInt(1);
xmlFile = "d:\\xml\\" + fjbh + ".xml";
Clob clob = rs.getClob(16);
FileOutputStream fo = new FileOutputStream(xmlFile);
OutputStreamWriter so = new OutputStreamWriter(fo, "UTF-8");
if (clob != null) {
Reader is = clob.getCharacterStream();
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
while (s != null) {
so.write(s + System.getProperty("line.separator"));
// System.out.println(str);
s = br.readLine();
}
}
so.flush();
so.close();
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
DB.close(rs);
DB.close(stmt);
DB.close(conn);
return xmlFile;
}
public static void updateClob(String fileName, int id) {
FileInputStream fis = null;
InputStreamReader rd = null;
try {
fis = new FileInputStream(fileName);
rd = new InputStreamReader(fis, "UTF-8");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PreparedStatement pst = null;
Connection conn = DB.getConn();
Statement stmt = DB.createStmt(conn);
try {
conn.setAutoCommit(false);
} catch (SQLException e1) {
e1.printStackTrace();
}
String sql1 = "update BD_PROCESS_DEF_VER s set s.NODE_INFO=' ' where ID="
+ id; // 这边需要设置一个空的字段,后面就不会出现空指针
try {
stmt.execute(sql1);
} catch (SQLException e) {
e.printStackTrace();
}
String sql2 = "select * from BD_PROCESS_DEF_VER s where s.ID=" + id;
// 锁定数据行进行更新,注意“for update”语句
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql2);
} catch (SQLException e) {
e.printStackTrace();
}
try {
while (rs.next()) {
String sql3 = "update BD_PROCESS_DEF_VER set NODE_INFO= ? where ID="+ id;
pst = conn.prepareStatement(sql3);
pst.setCharacterStream(1, rd, 100000000);
pst.executeUpdate();
}
// 最后一步自己提交
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(rs);
DB.close(stmt);
try {
pst.close(