Using PL/SQL Function with CLOB types and a Java Source
722963Dec 22 2009 — edited Jan 4 2010Hi people.
I have some problems trying to use a function in pl/sql with a CLOB parameter to a java source function.
Here is the problem: I have to read a TXT file and return a CLOB with the data of the file. The reading is done with a java source function.
The problem is how to read the file without messing the content and return it to the pl/sql function?
Another problem: If I pass a CLOB as a parameter to a pl/sql function and have to write the content to a file, how to do it without screwing the EOL chars and so?
My code is:
-----
/******** PLSQL FUNCTIONS ********/
function fn_gravaconteudoarquivo( pv_caminho in varchar2
, pv_nomearquivo in varchar2
, pc_conteudo in clob ) return varchar2 as language java
name 'Importacao.gravaConteudoArquivo(java.lang.String, java.lang.String, oracle.sql.CLOB) return varchar2';
function fn_lerconteudoarquivoclob( pv_caminho in varchar2
, pv_nomearquivo in varchar2 ) return clob as language java
name 'Importacao.lerArquivoClob(java.lang.String, java.lang.String) return clob';
-----
/******** JAVA SOURCE FUNCTIONS *********/
public static String gravaConteudoArquivo(String caminho, String nomeArquivo, CLOB conteudo) {
File file = new File(caminho, nomeArquivo);
PrintWriter pwFile;
String mensagem = "";
StringBuffer sb = new StringBuffer();
try {
pwFile = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
for (int i=0;i<=(conteudo.length()/32000);i++) {
sb.append(conteudo.getSubString(conteudo.getLength()+1,32000));
}
pwFile.println(sb.substring(0));
pwFile.close();
} catch (Exception ex) {
mensagem = "Erro: "+ex;
}
return mensagem;
}
public static CLOB lerArquivoClob(String caminho, String nomeArquivo) throws SQLException {
File file = new File(caminho, nomeArquivo);
Connection conn;
CLOB clob = null;
String lineSep = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:csdesv", "csestoque", "liberada");
clob = CLOB.createTemporary(conn, true, CLOB.DURATION_SESSION);
BufferedReader brFile = new BufferedReader(new FileReader(file.getPath()));
while (brFile.ready()) {
sb.append(brFile.readLine());
sb.append(lineSep);
}
clob.open(CLOB.MODE_READWRITE);
clob.setString(clob.getLength()+1, sb.toString());
clob.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return clob;
}
-----
Ah, just remembered... This will work as a JOB.... >.< ... So the connection aparently is at localhost.
Thanks.