Java-Stored Procedure retornando "Cursor"

Dúvidas, dicas e truques de PL/SQL. Aqui também vão assuntos relacionados a pacotes, triggers, funções, Java-Stored Procedures, etc
Responder
davidguerra
Rank: Estagiário Júnior
Rank: Estagiário Júnior
Mensagens: 2
Registrado em: Seg, 03 Mar 2008 11:09 am
Localização: CE

PessoALL,

Estou criando uma classe para funcionar como um mini Database link do Oracle para outros bancos.

Mas eu não estou conseguindo montar um cursor para retornar por essa procedure. Eu só consegui fazer com que, quando eu chame esse método, ele crie uma tabela idêntica à tabela do outro banco (PostgreSQL, por exemplo) no oracle.

Mas... Eu não queria criar essa tabela cópia... E sim... Só retornar para a consulta atual.

Segue o código abaixo:

Selecionar tudo

create or replace and compile java source named webservice as
import java.net.*;
import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import java.sql.*;
import oracle.jdbc.*;

public class WebService
{
  private static final String ENDERECO = "http://******";
  private static final String BANCO = "POSTGRESQL";
  private static final String IP = "******";
  private static final int PORTA = ******;
  private static final String SERVICO = "******";
  private static final String USUARIO = "******";
  private static final String SENHA = "******";
  
  private static Connection oConn = null;
  
	public static void criarTabela (String nomeTabela, String parametros) throws Exception
	{
    CallableStatement stmt;
    String strQ = "create table " + nomeTabela + " (";
    strQ += parametros;
    strQ += ")";

		try {
        stmt = oConn.prepareCall("drop table " + nomeTabela);
        stmt.execute();
    } catch (Exception e) {}

 		stmt = oConn.prepareCall(strQ);
    stmt.execute();
  }
  
  private static void adicionarLinha(Node nl, String tabela, String[] nomeParametros) throws Exception {
    String strQ = "INSERT INTO " + tabela + " VALUES (";
    CallableStatement stmt;
    
    for (int i=0;i<nomeParametros.length;i++) {
        if (i!=0) {
           strQ += ", ";
        }
        strQ += "'" + nl.getAttributes().getNamedItem(nomeParametros[i]).getNodeValue() + "'";
    }
    strQ += ")";
 		stmt = oConn.prepareCall(strQ);
    stmt.execute();
  }
   
	public static void consulta (String nomeView, String nomeTabela) throws Exception	{
    consulta (ENDERECO, BANCO, IP, PORTA, SERVICO, USUARIO, SENHA, nomeView, nomeTabela);
  }
  
	public static void consulta (String endereco, String banco, String ip, int porta, String servico, String usuario, String senha, String nomeView, String nomeTabela) throws Exception	{

		StringBuffer response = new StringBuffer();
		String placa = null;
    String strUrl = endereco + "?txtBanco=" + banco + "&txtIp=" + ip + "&txtPorta=" + porta + "&txtServico=" + servico + "&txtUsuario=" + usuario + "&txtSenha=" + senha + "&txtSql=SELECT%20*%20FROM%20" + nomeView;
		DOMParser parser = new DOMParser();
		URL url = new URL(strUrl);
		parser.setErrorStream(System.err);
		parser.showWarnings(true);
		parser.parse(url);
		XMLDocument doc = parser.getDocument();

		String erro = "";

		XMLElement nsElement;

		NodeList nl = doc.getElementsByTagName("FIELD");
		Node params = doc.getElementsByTagName("PARAMS").item(0);
		erro = params.getAttributes().getNamedItem("ERRO").getNodeValue();
		if (erro!=null&&!erro.equals("")) {
			throw new Exception(erro);
		}
    String parametros = "";
    String[] nomeParametros = new String[nl.getLength()];
		for (int i = 0; i < nl.getLength(); i++) {
        if (i!=0) {
           parametros += ", ";
        }
        parametros += nl.item(i).getAttributes().getNamedItem("attrname").getNodeValue() + " " + nl.item(i).getAttributes().getNamedItem("fieldtype").getNodeValue() + "(" + nl.item(i).getAttributes().getNamedItem("WIDTH").getNodeValue() + ")";   
        nomeParametros[i] = nl.item(i).getAttributes().getNamedItem("attrname").getNodeValue();
 		}
    try {
        oConn = new OracleDriver().defaultConnection();
        criarTabela(nomeTabela,parametros);
 		    nl = doc.getElementsByTagName("ROW");
		    for (int i = 0; i < nl.getLength(); i++) {
            adicionarLinha(nl.item(i),nomeTabela,nomeParametros);
 		    }
        oConn.commit();
    } catch (Exception e) {
        oConn.close();
        oConn = null;
        throw e;
    }
		parser.reset();
	}
}
;
victorhugomuniz
Moderador
Moderador
Mensagens: 1396
Registrado em: Sex, 01 Fev 2008 2:06 pm
Localização: Rio de Janeiro - RJ
Contato:
:D

tomara que alguém te ajude pois eu não entendi nada do que você falou e muito menos do seu codigo
davidguerra
Rank: Estagiário Júnior
Rank: Estagiário Júnior
Mensagens: 2
Registrado em: Seg, 03 Mar 2008 11:09 am
Localização: CE

hehehe

É o seguinte... Esse código acessa uma URL que retorna o conteúdo de um select, em formato XML. Com a descrição dos tipos de colunas. Baseado nesse retorno, eu crio uma tabela temporária com a mesma estrutura e dados.

O que eu estou tentando fazer é, baseado nesse retorno XML, montar um cursor com os dados que eu tenho, sem a necessidade de criar essa tabela temporária.

Seria mais ou menos assim:

SELECT * FROM getPostgreSQL('SELECT * FROM TBLUSUARIO') ;

A função getPostgreSQL() retornaria um cursor. Assim eu não precisaria criar uma tabela temporária com uma estrutura e dados igual ao TBLUSUARIO (tabela no PostgreSQL).

Atualmente eu faço assim:

BEGIN gerarTabela('TBLUSUARIO','TBLUSUARIO_TEMP'); END;

Essa procedure cria uma tabela temporária, no Oracle, idêntica a oficial do PostgreSQL.

Estou procurando uma maneira mais flexível e sem precisar criar tabelas temporárias para o problema.

Melhorou um pouco?

Valeu. :)
Responder
  • Informação
  • Quem está online

    Usuários navegando neste fórum: Nenhum usuário registrado e 19 visitantes