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

  1.执行clobString

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();
    }
  }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zywxsd.html