oracle数据库中将clob字段内容利用java提取出至…

2018-12-24 09:08:39来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

代码段:

  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数据库连接、基本读取集合内容至文本文档。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:初识RabbitMQ

下一篇:Java实现进程调度算法(二) RR(时间片轮转)