Advertisement
JVFabia

JDBC ps

Oct 5th, 2020
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.42 KB | None | 0 0
  1.  
  2. package org.forge;
  3.  
  4. import java.sql.*;
  5. import java.util.Scanner;
  6.  
  7. public class Main {
  8.  
  9.     public static void main(String[] args) {
  10.         // nombre = Juan Perez
  11.         // rut=  25.542.569-8
  12.         // user = jperez
  13.         // password = P25.54
  14.         // url = forgedb.netbyteoss.com
  15.         // puerto = 5443
  16.         // base de datos = forge_alumnos
  17.         try {
  18.             try {
  19.                 Class.forName("org.postgresql.Driver");
  20.             } catch (ClassNotFoundException ex) {
  21.                 System.out.println("Error, el driver de PostgresSQL no se ha cargado : " + ex);
  22.             }
  23.             Connection conn = null;
  24.             // Conectamos con la base de datos
  25.             conn = DriverManager.getConnection(  "jdbc:postgresql://forgedb.netbyteoss.com:5443/forge_alumnos",                    "jperez", "P25.54");
  26.  
  27.             // Proceso para recuperar nombre del teclado
  28.             Scanner sc = new Scanner(System.in);
  29.             System.out.println(" Ingrese su nombre ");
  30.             String nombre = sc.nextLine();
  31.             System.out.println(" Ingrese su apellido ");
  32.             String apellido = sc.nextLine();
  33.             // Consulta a la bd (string)
  34.             String consulta = "select * from ejercicios where nombre = ? and apellido = ? ";
  35.             // Preparacion de consulta y enlace a conexion
  36.             PreparedStatement ps = conn.prepareStatement(consulta);
  37.             // Agregamos parametro de teclado
  38.             ps.setString(1, nombre);
  39.             ps.setString(2, apellido);
  40.             System.out.println(ps);
  41.  
  42.             // Variable que almacenara el retorno de nuestra consulta
  43.             ResultSet rs = ps.executeQuery();
  44.             // Para recorrer las tuplas en este caso ocuparemos while
  45.             while (rs.next()){
  46.                 //De acuerdo al tipo de dato de atributo en la bd usamos los metodos de rs al ser strin rs.getString(nombre atributo)
  47.                 System.out.println("Su nombre es  : " +  rs.getString("nombre") + " "+  rs.getString("apellido") );
  48.                 System.out.println("De nacionalidad  : " +  rs.getString("nacionalidad") + " esta en "+  rs.getString("ciudad") );
  49.                 System.out.println("Su seria favorita es   : " +  rs.getString("serie") + " y deporte  "+  rs.getString("deporte") );
  50.             }
  51.  
  52.         } catch (java.sql.SQLException sqle) {
  53.             System.out.println("Error:" + sqle);
  54.         }
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement