martes, 9 de julio de 2013

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;
        }
    }
}

No hay comentarios:

Publicar un comentario