quarta-feira, 19 de junho de 2013

Exportar Tabela Sql para CSV

Método simples e eficaz de exportar uma tabela de algum banco de dados para um arquivo CSV.
Útil para quando não se tem acesso ao editor do banco para exportar os dados.

Precisa apenas do Session com o Hibernate já criado (exemplo) para a função saber em qual banco conectar.

Função:
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;



public class ExportTableToCsv {

 /**
  * @param args
  * @throws Exception 
  */
 public static void main(String[] args) throws Exception {
  exportTableToCsv("CAD_CLIENTE", new File("C:\\temp\\out.csv"), HibernateSessionFactory.getSession());
  
  System.out.println("OK");
 }
 
 /**
  * Export table to CSV file.
  * @param table: name of table
  * @param fileOut: file where you saved the CSV
  * @param em: Input the "org.hibernate.Session", session connection to the database
  * @throws Exception
  */
 private static void exportTableToCsv(String table, File fileOut, Session em) throws Exception{
  Transaction trans = em.beginTransaction();
  try {
   Query query = em.createSQLQuery("SELECT COLUMNS.NAME AS COLUNA "+
     "FROM SYSOBJECTS AS TABLE, "+
     "     SYSCOLUMNS AS COLUMNS "+
     "WHERE TABLE.ID = COLUMNS.ID "+
     "  AND TABLE.NAME = '"+table+"' ");
   @SuppressWarnings("rawtypes")
   List list = query.list();
   if(list.size()==0){
    throw new Exception("Table '"+table+"' does not exist.");
   }
   
   String texto = "";
   for (int i = 0; i < list.size(); i++) {
    texto+= (String) list.get(i) + ";";
   }
   texto+="\n";
   

   query = em.createSQLQuery("SELECT * FROM "+table);
   list = query.list();
   trans.commit();
   
   for (int i = 0; i < list.size(); i++) {
    Object[] object = (Object[]) list.get(i);

    for (Object obj : object) {
     if(obj!=null){
      texto+= obj.toString().replace(";","|") + ";";
     }else{
      texto+= "null;";
     }
    }
    texto+="\n";
   }
   
   FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
   fileOutputStream.write(texto.getBytes());
   
   fileOutputStream.flush();
   fileOutputStream.close();
  } catch (Exception e) {
   e.printStackTrace();
   if (trans!=null&&trans.isActive()) {
    trans.rollback();
   }
   throw e;
  } finally {
   em.close();
  }
 }
}


Por hoje é isso pessoal.
COMPARTILHE, COMENTE, AGRADEÇA.


Nenhum comentário:

Postar um comentário