martes, 9 de julio de 2013

CU1.- Agregar un seguro



JDBC Driver oracle

Para conectarse a Oracle puedes indicar que método necesitas:

OCI http://docs.oracle.com/cd/B19306_01/java.102/b14355/instclnt.htm  o thin http://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Oracle Thin JDBC utilizando un nombre de servicio:

jdbc: oracle: thin: @ / / <host>: <puerto> / <nombre_servicio>

Ejemplo: jdbc: oracle: thin: @ / / 192.168.2.1:1521 / XE


Oracle Thin JDBC usando un SID:

jdbc: oracle: thin: @ <host>: <puerto>: <SID>

Ejemplo: jdbc: oracle: thin: 192.168.2.1:1521: X01A

Nota: El soporte de SID se está eliminando. Oracle recomienda que los usuarios pasen a utilizar nombres de servicio.


Oracle Thin JDBC usando un TNSNAME:

jdbc: oracle: thin: @ <TNSName>

Ejemplo: jdbc: oracle: thin: @ GL

Nota: El soporte para TNSNAMES se añadió en la versión del controlador 10.2.0.1


Oracle JDBC OCI formato de controlador


jdbc: oracle: oci: @ <database_name>

Ejemplo: jdbc: oracle: oci: @ HR

Conección a base de datos con Java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package revisaaudio;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author cele mediateca
 */
public class BD {

    private String host;
    private String bd;
    private String user;
    private String pwd;
    private String Driver;
    private Connection cnn;

    public BD(String host, String bd, String user, String pwd) throws ClassNotFoundException, SQLException {
        this.host = host;
        this.bd = bd;
        this.user = user;
        this.pwd = pwd;
        // System.out.println("Conectandose a host:"+host+" bd"+bd+" usuario:"+user+" pass:"+pwd);
        Class.forName("org.postgresql.Driver");
        cnn = DriverManager.getConnection("jdbc:postgresql://" + host + "/" + bd, user, pwd);
    }

    public BD(String config) throws ClassNotFoundException, SQLException {
        try {

            if (!config.endsWith(".properties")) {
                ArrayList<String> leeArchivoCadena = RevisaAudio.leeArchivoCadena(config);
                if (leeArchivoCadena.size() != 7) {
                    throw new Exception("No hay suficientes parametros para conectar a la base " + leeArchivoCadena);
                }
                host = leeArchivoCadena.get(0).trim();
                bd = leeArchivoCadena.get(1).trim();
                user = leeArchivoCadena.get(2).trim();
                pwd = leeArchivoCadena.get(3).trim();
                Driver = leeArchivoCadena.get(4).trim();
            } else {
                Properties prop = new Properties();
                prop.load(new FileInputStream(config));
                host = prop.getProperty("host");
                bd = prop.getProperty("bd");
                user = prop.getProperty("user");
                pwd = prop.getProperty("pwd");
                Driver = prop.getProperty("driver");
            }

            Class.forName("org.postgresql.Driver");
            cnn = DriverManager.getConnection("jdbc:postgresql://" + host + "/" + bd, user, pwd);

            // cnn = DriverManager.getConnection("jdbc:postgresql://" + host + "/" + bd, user, pwd);
        } catch (Exception ex) {
            ex.printStackTrace();
            
        }
    }
    /*
     public BD(int i, String config) throws ClassNotFoundException, SQLException {
     try {
     ArrayList<String> leeArchivoCadena = RevisaAudio.leeArchivoCadena(config);
     if (leeArchivoCadena.size() != 5) {
     throw new Exception("No hay suficientes parametros para conectar a la base " + leeArchivoCadena);
     }
     host = leeArchivoCadena.get(0).trim();
     bd = leeArchivoCadena.get(1).trim();
     user = leeArchivoCadena.get(2).trim();
     pwd = leeArchivoCadena.get(3).trim();
     Driver = leeArchivoCadena.get(4).trim();


     // cnn = DriverManager.getConnection("jdbc:postgresql://" + host + "/" + bd, user, pwd);
     } catch (Exception ex) {
     Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
     }
     }
     */
    /* private void inicializaParametros() {
     host = "localhost:5432";
     bd = "dspace1";
     user = "dspace1";
     pwd = "dspace1";
     }
    
     private Connection conecta() {
     try {
     Class.forName("org.postgresql.Driver");
     return DriverManager.getConnection("jdbc:postgresql://" + host + "/" + bd, user, pwd);
     } catch (Exception ex) {
     Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
     return null;
     }
     }
     */

    /**
     * *****Inicia funcion ejecutaSqlDate********
     */
    public Date ejecutaSqlDate(String sql) {
        //select count(*) from comentarios


        try {

            ResultSet rs = cnn.createStatement().executeQuery(sql);

            if (rs.getMetaData().getColumnCount() == 1 && rs.next()) {
                return rs.getDate(1);
            }
            throw new Exception("El query no regreso nada!!!!!!! query recibido -> " + sql);

        } /**
         * * Cerrar Conexion ****
         */
        catch (Exception e) {
            e.printStackTrace();

            return null;
        }  

    }

    /**
     * * fin ejecutaSqlDate ****
     */
    /**
     * *****Inicia funcion ejecutaSqlString********
     */
    public String ejecutaSqlString(String sql) {
        //select count(*) from comentarios


        try {

            ResultSet rs = cnn.createStatement().executeQuery(sql);

            if (rs.getMetaData().getColumnCount() == 1 && rs.next()) {
                return rs.getString(1);
            }
            throw new Exception("El query no regreso nada!!!!!!! query recibido -> " + sql);

        } /**
         * * Cerrar Conexion ****
         */
        catch (Exception e) {
            e.printStackTrace();
            String er = "error";
            return er;
        }  

    }

    /**
     * * fin ejecutaSqlString ****
     */
    /**
     * *****Inicia funcion ejecutaSqldouble********
     */
    public double ejecutaSqlDouble(String sql) {
        //select count(*) from comentarios


        try {

            ResultSet rs = cnn.createStatement().executeQuery(sql);

            if (rs.getMetaData().getColumnCount() == 1 && rs.next()) {
                return rs.getDouble(1);
            }
            throw new Exception("El query no regreso nada!!!!!!! query recibido -> " + sql);

        } /**
         * * Cerrar Conexion ****
         */
        catch (Exception e) {
            e.printStackTrace();

            return -1;
        }  

    }

    /**
     * * fin ejecutaSqlDouble ****
     */
    /**
     * *****Inicia funcion ejecutaSqlInt********
     */
    public int ejecutaSqlInt(String sql) {
        //select count(*) from comentarios

        int cols = 0;
        try {

            ResultSet rs = cnn.createStatement().executeQuery(sql);

            if (rs.getMetaData().getColumnCount() == 1 && rs.next()) {
                return rs.getInt(1);
            }
            throw new Exception("El query no regreso nada!!!!!!! query recibido " + sql);

        } /**
         * * Cerrar Conexion ****
         */
        catch (Exception e) {
            e.printStackTrace();

            return -1;
        }  

    }

    /**
     * * fin ejecutaSqlInt ****
     */
    public boolean ejecutaUpdate(String sql) {

        try {

            int res = cnn.createStatement().executeUpdate(sql);

            return res > 0;
        } catch (Exception e) {

            e.printStackTrace();
            return false;
        } 


    }

    public ArrayList<String[]> ejecutaSql(String sql) {

        ArrayList<String[]> res = new ArrayList<String[]>();
        try {



            ResultSet rs = cnn.createStatement().executeQuery(sql);
            int cols = rs.getMetaData().getColumnCount();
            //  System.err.println(sql);
            while (rs.next()) {
                String[] ren = new String[cols];
                for (int j = 1; j <= cols; j++) {
                    ren[j - 1] = rs.getString(j);

                }
                res.add(ren);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }  
        return res;

    }

    public String[] ejecutaSqlLine(String sql) {

        String[] ren = null;
        try {


            ResultSet rs = cnn.createStatement().executeQuery(sql);
            int cols = rs.getMetaData().getColumnCount();
            //  System.err.println(sql);
            while (rs.next()) {
                ren = new String[cols];
                for (int j = 1; j <= cols; j++) {
                    ren[j - 1] = rs.getString(j);

                }



            }
        } catch (Exception e) {
            e.printStackTrace();
        }  
        return ren;

    }

    public Connection getCnn() {
        return cnn;
    }

    public void close() {
        if (cnn != null) {
            try {
                cnn.close();
            } catch (SQLException ex) {
                Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
            }
            cnn = null;
        }
    }
}

viernes, 5 de julio de 2013

Clase AdminBase

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logica;

import datos.admin.AdminPersona;
import datos.dominio.Persona;



/**
 *
 * @author DAS
 */
public class AdminBase {
   
    public static void main(String[] args) {
        int numPersonas=10;
       Persona[] primerasPersonasenLista=
               AdminPersona.lstPersona(numPersonas);
        for (int i = 0;
                i < primerasPersonasenLista.length;
                i++) {
           
            System.out.println("Persona #"+(i+1)+
                    ".- "+primerasPersonasenLista[i]);
           
        }
    }
   
}

Clase AdminPersona

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datos.admin;

import datos.dominio.Persona;

/**
 *
 * @author DAS
 */
public class AdminPersona {
   
    public static void agrPersona(Persona p){
        //accso a la bd e inserto
    }
    public static void brrPersona(Persona p){
        //accso a la bd e inserto
    }
    public static void actlzPersona(Persona p){
        //accso a la bd e inserto
    }
   
    public static Persona[] lstPersona(int tam){
        //arreglo de objetos
        Persona [] seleccionados= new Persona[tam];
        String abc="ABCDEFGHIJKLMNOPQRSTUV";
        for (int i = 0; i < seleccionados.length; i++) {
            //Persona persona = personas[i];
            //sql="select ....."
            //JDBC query regresa
            seleccionados[i]= new Persona("nombre  "+abc.charAt(i)
                    , null, null);
            //constructor de la clase
        }
        return seleccionados;
       
        //accso a la bd e inserto
    }
           
   
}

Clase Persona

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datos.dominio;

import java.util.Objects;

/**
 *
 * @author DAS
 */
public class Persona {

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 23 * hash + Objects.hashCode(this.id);
        hash = 23 * hash + Objects.hashCode(this.nombre);
        hash = 23 * hash + Objects.hashCode(this.primerApellido);
        hash = 23 * hash + Objects.hashCode(this.segundoApellido);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Persona other = (Persona) obj;
        if (!Objects.equals(this.id, other.id)) {
            return false;
        }
        if (!Objects.equals(this.nombre, other.nombre)) {
            return false;
        }
        if (!Objects.equals(this.primerApellido, other.primerApellido)) {
            return false;
        }
        if (!Objects.equals(this.segundoApellido, other.segundoApellido)) {
            return false;
        }
        return true;
    }

    private Integer id = -1;
    String nombre = "Sin nombre";
    private String primerApellido = null;
    private String segundoApellido = null;

    public Persona() {
        nombre = "";
        primerApellido = "";
        segundoApellido = "";
    }

    public Persona(String nom, String pa, String sa) {
        try {
            //Validando en nombre      

          setNombre(nom);
            //Primer paterno
            if (pa == null || !pa.trim().isEmpty()
                    && pa.matches("[a-zA-Z áéíóíñÑ]+")
                    && pa.length() <= 60) {

                primerApellido = pa;
            } else {
                System.err.println("El texto: " + pa + ""
                        + " no es valido para el primer apellido");
            }

            //Segundo paterno
            if (sa == null || !sa.trim().isEmpty()
                    && sa.matches("[a-zA-Z áéíóíñÑ]+")
                    && sa.length() <= 60) {

                segundoApellido = sa;
            } else {
                System.err.println("El texto: " + sa + ""
                        + " no es valido para el segundo apellido");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            nombre = "Sin nombre";
            primerApellido = null;
            segundoApellido = null;
            throw ex;
        }

    }

    public String getNombre() {
        return nombre;
    }

    
    public void setNombre(String nom) {
        if (nom != null && !nom.trim().isEmpty()
                && nom.matches("[a-zA-Z áéíóíñÑ]+")
                && nom.length() <= 60) {
            //System.out.println("ok");
            nombre = nom;
        } else {
            System.err.println("El texto: " + nom + ""
                    + "No es valido para un nombre");
        }
    }

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the primerApellido
     */
    public String getPrimerApellido() {
        return primerApellido;
    }

    /**
     * @param primerApellido the primerApellido to set
     */
    public void setPrimerApellido(String primerApellido) {
        this.primerApellido = primerApellido;
    }

    /**
     * @return the segundoApellido
     */
    public String getSegundoApellido() {
        return segundoApellido;
    }

    /**
     * @param segundoApellido the segundoApellido to set
     */
    public void setSegundoApellido(String segundoApellido) {
        this.segundoApellido = segundoApellido;
    }

    @Override
    public String toString() {
        return "Mi toString:" + nombre();
    }

    public String nombre() {

        return nombre + " " + getPrimerApellido() + " " + getSegundoApellido();
    }

    public static void main(String[] args) {
        try {
            // Persona p = new Persona("Nombre", null, null);
            Persona p = new Persona();
            Persona p2 = new Persona("Nombre", null, null);
        } catch (Exception ex) {


            System.out.println("No se pudo crear el objeto persona");
        }
    }
}

jueves, 4 de julio de 2013

Clase persona

Código de la clase Persona




/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datos.dominio;

/**
 *
 * @author DAS
 */
public class Persona {

    String nombre = "Sin nombre";
    String primerApellido = null;
    String segundoApellido = null;

    public Persona(String nom, String pa, String sa) {
        try {
            //Validando en nombre      
            nom = null;
            nom.charAt(0);
            if (nom != null &amp;&amp; !nom.trim().isEmpty()
                    &amp;&amp; nom.matches("[a-zA-Z áéíóíñÑ]+")
                    &amp;&amp; nom.length() &lt;= 60) {
                //System.out.println("ok");
                nombre = nom;
            } else {
                System.err.println("El texto: " + nom + ""
                        + "No es valido para un nombre");
            }
            //Primer paterno
            if (pa == null || !pa.trim().isEmpty()
                    &amp;&amp; pa.matches("[a-zA-Z áéíóíñÑ]+")
                    &amp;&amp; pa.length() &lt;= 60) {

                primerApellido = pa;
            } else {
                System.err.println("El texto: " + pa + ""
                        + " no es valido para el primer apellido");
            }

            //Segundo paterno
            if (sa == null || !sa.trim().isEmpty()
                    &amp;&amp; sa.matches("[a-zA-Z áéíóíñÑ]+")
                    &amp;&amp; sa.length() &lt;= 60) {

                segundoApellido = sa;
            } else {
                System.err.println("El texto: " + sa + ""
                        + " no es valido para el segundo apellido");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            nombre = "Sin nombre";
            primerApellido = null;
            segundoApellido = null;
            throw ex;
        }

    }

    public String nombre() {

        return nombre + " " + primerApellido + " " + segundoApellido;
    }

    public static void main(String[] args) {
        try{
        Persona p = new Persona("Nombre", null, null);
        }catch(Exception ex){
           
           
            System.out.println("No se pudo crear el objeto persona");
        }
    }
}