Last active
May 31, 2019 22:30
-
-
Save vacax/d0025577b86a7c92dd0b7de3f09d9809 to your computer and use it in GitHub Desktop.
Clase_31052019 - Main
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.hmc; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) throws SQLException { | |
System.out.println("Hola Mundo Conexión"); | |
// | |
registrarDriver(); | |
// | |
Connection con = getConexion(); | |
System.out.println("Conectado a la base de datos...."); | |
con.close(); | |
List<Estudiante> lista = getListaEstudiante(); | |
for(Estudiante e : lista){ | |
System.out.println(e); | |
} | |
} | |
public static void registrarDriver(){ | |
try { | |
Class.forName("org.h2.Driver").newInstance(); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} catch (InstantiationException e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* | |
* @return | |
* @throws SQLException | |
*/ | |
public static Connection getConexion() throws SQLException { | |
String url = "jdbc:h2:tcp://localhost/~/holamundojdbc"; | |
String usuario = "sa"; | |
String password = ""; | |
Connection con = DriverManager.getConnection(url, usuario,password); | |
return con; | |
} | |
public static List<Estudiante> getListaEstudiante() throws SQLException{ | |
List<Estudiante> lista = new ArrayList<>(); | |
// | |
String sql = "select * from estudiante"; | |
// | |
Connection connection = getConexion(); | |
ResultSet resultSet = connection.createStatement().executeQuery(sql); | |
while (resultSet.next()){ | |
//iterar los resultados de la consulta... | |
Estudiante tmp = new Estudiante(); | |
tmp.setMatricula(resultSet.getInt("matricula")); | |
tmp.setNombre(resultSet.getString("nombre")); | |
// | |
lista.add(tmp); | |
} | |
connection.close(); | |
return lista; | |
} | |
static class Estudiante{ | |
int matricula; | |
String nombre; | |
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; | |
} | |
@Override | |
public String toString() { | |
return "Estudiante{" + | |
"matricula=" + matricula + | |
", nombre='" + nombre + '\'' + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment