package core;
import java.io.*;
import java.sql.*;
import common.*;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class ClobEx {
public static void addLob(int id, String binFile) throws SQLException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = ConnectionFactory.getFactory().getConnection();
con.setAutoCommit(false);
String sql = "INSERT INTO tbl_clob(id, remark) " +
"VALUES(?, ?)";
ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.setClob(2, oracle.sql.CLOB.empty_lob());
ps.executeUpdate();
DBUtils.close(ps);
ps = con.prepareStatement(
"SELECT remark FROM tbl_clob" +
" WHERE id = " + id);
rs = ps.executeQuery();
if (rs.next()) {
oracle.sql.CLOB remark =
(oracle.sql.CLOB)rs.getClob(1);
PrintWriter out = new PrintWriter(new OutputStreamWriter(remark.getAsciiOutputStream()));
BufferedReader in = new BufferedReader(
new FileReader(binFile));
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
in.close();
out.close();
}
con.commit();
} catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
} catch (SQLException se) {
}
throw new SQLException(e.getMessage());
} finally {
DBUtils.close(rs, ps, con);
}
}
public static void fetchLob(int id, String filename) throws SQLException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = ConnectionFactory.getFactory().getConnection();
String sql = "SELECT * from tbl_clob where id = " + id;
st = con.createStatement();
rs = st.executeQuery(sql);
if (rs.next()) {
oracle.sql.CLOB remark =
(oracle.sql.CLOB)rs.getClob("remark");
PrintWriter out = new PrintWriter(
new FileWriter(filename));
BufferedReader in = new BufferedReader(
new InputStreamReader(
remark.getAsciiStream(), "GB2312"));
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
in.close();
out.close();
}
} catch (Exception e) {
throw new SQLException(e.getMessage());
} finally {
DBUtils.close(rs, st, con);
}
}
public static void main(String[] args) throws Exception {
addLob(5, "test_u.txt");
fetchLob(5, "test_c.txt");
System.out.println("completed!");
}
}