Pegar campo com select

5 respostas
P

Estou fazendo um select no banco e tentando utilizar o valor retornado no meu app e depois gravar novamente no banco, mas tá dando erro. Deve ser tipo incompativel, alguém sabe como fazer essa conversão?

Statement stm = conn.createStatement();
      ResultSet rs = stm.executeQuery("select max(ICO_DATA) ico_data from internet_controle");
      while(rs.next()){
      rs.getInt("ico_data");
      }

if(rs < 1){
          rs = 1;
      }else{
          rs = rs + i;
      }

5 Respostas

K

Depende do tipo do campo do Oracle que voce está tentando recuperar se for data, acho que tem getDate, ou getTimestamp, de qualquer forma, pode utilizar o maleável método getObject("") que lhe retornará uma String.

Eu fiz uma jTable, que o model é montado de um DAO, ele seleciona as colunas, e define como TableHeader, depois se houver conteúdo, faz paginação e monta a tabela conforme o conteúdo, irei pegar o código depois e lhe mandarei, é bem útil, utilizando Java + Oracle.

Abraços.

P

Não seria:

if(rs.getInt("ico_data") < 1){
}
P

O meu grande problema é que tenho um campo que deverá ser autoincrementado no Oracle, então tentei fazer o auto incremento “na mão”, pego o valor maior no banco, faço o if dentro de um laço for que vai especificar a quantidade de registros que serão gravados e depois grava o novo valor no campo (no Oracle é um number). Só falta isso para disponibilizar o app.
já tentei converter mas acusa erro que não pode ser convertido. Olha todo o código aí:

package controlewebinternet;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import jxl.Cell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 *
 * @author petter
 */
public class Internet {
    
    private static Connection conn;
    private static int i = 0;
    private static String stringa1;
    private static String stringb2;
    private static String stringc3;
    private static String stringd4;
    private static String stringe5;
    private static double douf6;
    private static String stringg7;
    private static String stringh8;
    private static double doui9;
    private static String stringj10;
    private static int incremento;
  
    private static String normalizeIP;
    public static String normalizeIP (String ip) throws UnknownHostException {
         InetAddress addr = InetAddress.getByName (ip);
         return addr.getHostAddress();
     }
    
    /** Creates a new instance of Main */
    public static void main(String[] args ) throws IOException, BiffException, 
                                                   ClassNotFoundException, SQLException, 
                                                   ParseException {
     
      //Dados para a conexão ao banco de dados
      String driverName = "oracle.jdbc.driver.OracleDriver";
      String serverName = "ip:port:data"; 
      String username = "user"; 
      String password = "senha"; 
      String url = "jdbc:oracle:thin:@"+serverName ;
        
      //Conexão com o banco de dados        
      Class.forName(driverName);
      Connection conn = DriverManager.getConnection(url, username, password);  
     
      //Pega o último valor do campo ID para auto-incremento
      Statement stm = conn.createStatement();
      ResultSet rs = stm.executeQuery("select max(ICO_DATA) ico_data from internet_controle");
      while(rs.next()){
      rs.getObject("ico_data");
      }
      
      /* pega o arquivo do Excel */
      Workbook workbook = Workbook.getWorkbook(new File("acesso.xls"));  
      
      /* pega a primeira planilha dentro do arquivo XLS */
      Sheet sheet = workbook.getSheet(0); 
     
      //Pega a quantidade de linhas da planilha
      int linhas = sheet.getRows();
      
      //Laço para fazer o looping para gravar todas as linhas da planilha
      for(i = 0; i < linhas; i++){
      /* pega os valores das células como se numa matriz */
      Cell a1 = sheet.getCell(0,i);
      Cell b2 = sheet.getCell(1,i);
      Cell c3 = sheet.getCell(2,i);
      Cell d4 = sheet.getCell(3,i);
      Cell e5 = sheet.getCell(4,i);
      Cell f6 = sheet.getCell(5,i);
      Cell g7 = sheet.getCell(6,i);
      Cell h8 = sheet.getCell(7,i);
      Cell i9 = sheet.getCell(8,i);
      Cell j10 = sheet.getCell(9,i);

      /* pega os conteúdos das células */
      stringa1 = a1.getContents();
      
      stringb2 = b2.getContents();
      
      stringc3 = c3.getContents();
      normalizeIP = normalizeIP(stringc3);
      
      stringd4 = d4.getContents();
      stringe5 = e5.getContents();
      
      NumberCell nc = (NumberCell)f6;
      douf6 = nc.getValue();
      int intf6;
      intf6 = (int)douf6;
      
      stringg7 = g7.getContents();
      stringh8 = h8.getContents();
      
      NumberCell nc2 = (NumberCell)i9;
      doui9 = nc2.getValue();
      int inti9;
      inti9 = (int)doui9;
      
      stringj10 = j10.getContents();
      
      //Incrementa o número da ID conforme o último registro pesquisado
     if(rs < 1){
          rs = 1;
      }else{
          rs = rs + i;
      }
        
     /*Executa o insert para inserir os dados no banco de testes MySQL*/     
     PreparedStatement ps = conn.prepareStatement("INSERT INTO INTERNET_CONTROLE(ICO_ID,ICO_DATA," +
             "                                                      ICO_IP,ICO_CONEXAO,ICO_BYTES," +
             "                                                      ICO_TEMPO) "+
             "VALUES('"+rs+"','"+stringb2+"','"+normalizeIP+"','"+stringe5+"'" +
          "         ,'"+intf6+"','"+inti9+"')");
         
     ps.executeUpdate(); 
     }
     workbook.close();
     
     //Gera mensagens com dados sobre a atualização do banco
     if(linhas == i){
         System.out.println("*** Atualização de acessos de Internet ***");
         System.out.println("Banco de dados atualizado referente ao dia " + stringb2 + ".");
         System.out.println("Total de registros gravados: " + linhas + ".");
         System.out.println("Aplicativo finalizado !");
     }
    }    
}
H

o rs.getObject(“ico_data”) vai retornar o valor deste campo com o seu respectivo tipo.

se ele é number o tipo é filho de Number assim…

Number num = null;

if(rs.next()){  //Troca o while por if

num = (Number)rs.getObject(ico_data);

}

int novoNumero = num.intValue() + 1;

e utiliza essa variavel no insert abaixo.

O mais correto é vc descobrir qual o tipo que esta vindo (Long, Integer, …)

Deve funcionar

P

Valeu cara.

Criado 5 de maio de 2006
Ultima resposta 5 de mai. de 2006
Respostas 5
Participantes 4