oracle数据库中将clob字段内容利用java提取出至文本文档中
代码段:
1.执行clob转string
public static string clobtostring(clob sc) throws sqlexception, ioexception {
string restring = "";
reader is = sc.getcharacterstream();
// 得到流
bufferedreader br = new bufferedreader(is);
string s = br.readline();
stringbuffer sb = new stringbuffer();
while (s != null) {
// 执行循环将字符串全部取出付值给stringbuffer由stringbuffer转成string
sb.append(s);
s = br.readline();
}
restring = sb.tostring();
return restring;
}
2.主类执行循环读取数据库+将转换内容存储至文本文档
public static void main(string[] args) {
connection connect = null;
statement statement = null;
resultset resultset = null;
resultset resultset1 = null;
preparedstatement prestate = null;
preparedstatement prestate1 = null;
try {
// 利用driver对象
driver driver = new oracledriver();
drivermanager.deregisterdriver(driver);
properties pro = new properties();
pro.put("user", "用户名");
pro.put("password", "密码");
connect = driver.connect("jdbc:oracle:thin:@地址:端口:数据库名", pro);
// 查询所有
string sql1 = "数据库相关查询语句";
prestate1 = connect.preparestatement(sql1);
resultset1 = prestate1.executequery();
while (resultset1.next()) {
//打印相关字段名,看看验证一下是否是想要的字段
system.out.println(resultset1.getstring("字段名"));
//定义其中变量(试个人数据库语句情况而定可取舍)
string str = resultset1.getstring("字段名");
//验证一下打印字段是否正确
system.out.println(str);
string sql = "相关查询语句";
prestate = connect.preparestatement(sql);
resultset = prestate.executequery();
while (resultset.next()) {
string content = clobtostring(resultset.getclob("自定义字段或表名"));
bufferedwriter bw = null;
try {
//相关路径为:src\\clobtest\\newfile.txt这个是我自己本地路径(视个人情况而修改)
bw = new bufferedwriter(new filewriter("src\\clobtest\\newfile.txt", true));
// for (int j = 0; j < 1; j++) {
bw.write(content + '\n');
// }
bw.flush();
} catch (ioexception e) {
e.printstacktrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (ioexception e) {
e.printstacktrace();
}
}
}
}
} catch (exception e) {
e.printstacktrace();
} finally {
//关闭资源
try {
if (resultset != null)
resultset.close();
if (prestate != null)
prestate.close();
if (statement != null)
statement.close();
if (connect != null)
connect.close();
} catch (sqlexception e) {
e.printstacktrace();
}
}
}
知识点:clob转换至string、jdbc:oracle数据库连接、基本读取集合内容至文本文档。