Advertisement
Guest User

Clase Conexion

a guest
May 12th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. package org.lilixips.transgenic.model;
  2.  
  3. import java.sql.Connection; // para establecer conxion con la base de datos.
  4. import java.sql.Statement;
  5. import java.sql.ResultSet;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8.  
  9. /**
  10.  *
  11.  * @author gzuñiga
  12.  */
  13. public class Conexion {
  14.  
  15.     private Connection con;
  16.     private Statement sentencia;
  17.     private ResultSet tablaVirtual;
  18.  
  19.     //Constructor
  20.     //Datos Necesarios.
  21.     /*
  22.         Servidor->localhost
  23.         user->root
  24.         pass->123456
  25.         bdName->bd_alimentos
  26.      */
  27.     public Conexion(String server, String user, String pass, String bdName) throws ClassNotFoundException, SQLException {
  28.         String prototolo = "jdbc:mysql://";
  29.         String lineaUsuario = "user=" + user;
  30.         String lineaPass = "password=" + pass;
  31.  
  32.         String url = prototolo + server + "/" + bdName + "?" + lineaUsuario + "&" + lineaPass;
  33.         System.out.println(url);
  34.  
  35.         //Cragar la clase driver en tiempo de ejecución.
  36.         Class.forName("com.mysql.jdbc.Driver");
  37.  
  38.         //Rescatar el objeto Conexion desde el Driver
  39.         con = DriverManager.getConnection(url);
  40.  
  41.     }
  42.  
  43.     public void ejecutar(String query) throws SQLException {
  44.         //1.- Crear la sentencia a través de la conexión.
  45.         // Abrir la conexión.
  46.         sentencia = con.createStatement();
  47.         //2.- Ejecutar un QUERY
  48.         sentencia.execute(query);
  49.         //3.- Cerrar la conexión->desconectar();
  50.         desconectar();
  51.         System.out.println(query);
  52.     }
  53.  
  54.     public ResultSet ejecutarSelect(String select) throws SQLException {
  55.         sentencia = con.createStatement();
  56.         tablaVirtual = sentencia.executeQuery(select);
  57.  
  58.         return tablaVirtual;
  59.     }
  60.  
  61.     public void desconectar() throws SQLException {
  62.         sentencia.close();
  63.     }
  64.  
  65. //    public static void main(String[] args) throws ClassNotFoundException, SQLException {
  66. //        Conexion c = new Conexion("localhost", "root", "123456", "bd_alimentos");
  67. //
  68. //        String insert = "INSERT INTO alimento VALUES(NULL,'Loly','Sabory',true);";
  69. //        c.ejecutar(insert);
  70. //    }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement