public class TestCLOB {
static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
static String driver = "oracle.jdbc.driver.OracleDriver";
static String userName = "scott";
static String pwd = "tiger";
public static void main(String[] args) {
try {
addCLOB();
// readCLOB();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readCLOB() throws ClassNotFoundException, SQLException, IOException
{
Class.forName(driver);// 加载数据库驱动
Connection con = DriverManager.getConnection(url, userName, pwd);
con.setAutoCommit(false);
PreparedStatement pstm = con.prepareStatement("select myClob from p_w_upload where id=1");
ResultSet rs = pstm.executeQuery();
CLOB clob = null;
if(rs.next())
{
clob = (CLOB) rs.getClob(1);
}
BufferedReader br = new BufferedReader(clob.getCharacterStream());
File file = new File("D:\\aad.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String s = null;
while((s = br.readLine())!=null)
{
bw.write(s);
bw.newLine();
}
bw.close();
br.close();
con.close();
}
public static void addCLOB() throws ClassNotFoundException, SQLException, IOException {
Class.forName(driver);// 加载数据库驱动
Connection con = DriverManager.getConnection(url, userName, pwd);
con.setAutoCommit(false);
Statement stmt = con.createStatement();
String initSql = "UPDATE ATTACHMENT SET MYCLOB=EMPTY_CLOB() WHERE ID=1";
// 读取CLOB字段
String updateSql = "SELECT MYCLOB FROM ATTACHMENT WHERE ID=1";
stmt.executeUpdate(initSql);
ResultSet rs = stmt.executeQuery(updateSql);
if (rs.next()) {
CLOB clob = (CLOB) rs.getClob(1); // 获取CLOB字段内容并转换为oracle.sql.CLOB类型
Writer os = clob.setCharacterStream(1); // 获取CLOB的输出流
BufferedReader br = new BufferedReader(new FileReader(new File("F:\\abc.txt"))); // 读取文本文件
String line = br.readLine();
StringBuffer buffer = new StringBuffer();
while (line != null) {
buffer.append(line+"\r\n");
line = br.readLine();
}
os.write(buffer.toString());
os.flush();
br.close();
os.close();
con.commit();
con.close();
}
System.out.println("Saved");
}
}
转载于:https://blog.51cto.com/9882931/1615102