Last active
February 7, 2019 22:25
-
-
Save vacax/cc7d4e2e8abae334ee4ddf98a70d9e50 to your computer and use it in GitHub Desktop.
Clase JDBC ejemplo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package edu.pucmm.pw.hmj; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
System.out.println("Hola Mundo JDBC"); | |
Conexion conexion = new Conexion(); | |
Connection con = conexion.getConexion(); | |
System.out.println("Base de datos conectada...."); | |
con.close(); | |
System.out.println("La cantidad de estudiantes: "+conexion.getListaEstudiantes().size()); | |
} | |
static class Conexion{ | |
Conexion(){ | |
registrarDriver(); | |
} | |
/** | |
* Registrar el Driver.... | |
*/ | |
private void registrarDriver(){ | |
try { | |
Class.forName("org.h2.Driver").newInstance(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* | |
* @return | |
* @throws Exception | |
*/ | |
public Connection getConexion() throws Exception{ | |
Connection connection = DriverManager.getConnection("jdbc:h2:~/holamundojdbc", "sa", ""); | |
return connection; | |
} | |
public List<Estudiante> getListaEstudiantes() throws Exception{ | |
List<Estudiante> lista = new ArrayList<>(); | |
Connection con = getConexion(); | |
PreparedStatement preparedStatement = con.prepareStatement("select * from ESTUDIANTE"); | |
//parametros los agregos. | |
//ejecuto la sentencia | |
ResultSet r = preparedStatement.executeQuery(); | |
while(r.next()){ | |
Estudiante estudiante =new Estudiante(); | |
estudiante.setMatricula(r.getInt("matricula")); | |
estudiante.setNombre(r.getString("nombre")); | |
estudiante.setDireccion(r.getString("direccion")); | |
lista.add(estudiante); | |
} | |
r.close(); | |
preparedStatement.close(); | |
con.close(); //todos los recursos abierto se cierran. | |
return lista; | |
} | |
} | |
static class Estudiante{ | |
private int matricula; | |
private String nombre; | |
private String direccion; | |
public int getMatricula() { | |
return matricula; | |
} | |
public void setMatricula(int matricula) { | |
this.matricula = matricula; | |
} | |
public String getNombre() { | |
return nombre; | |
} | |
public void setNombre(String nombre) { | |
this.nombre = nombre; | |
} | |
public String getDireccion() { | |
return direccion; | |
} | |
public void setDireccion(String direccion) { | |
this.direccion = direccion; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment