Guest User

Untitled

a guest
Nov 26th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. package agenda;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10.  
  11.  
  12. public class amigos{
  13.  
  14. public static void main(String[] args) throws SQLException {
  15.  
  16. try {
  17. Class.forName("com.mysql.jdbc.Driver"); //Inicializa el conector para MySQL
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/test", "usuario", "password"); // Especifica datos de la Base de Datos
  22. Statement s = conexion.createStatement(); // Crea un objeto de consulta de la conexion a la base
  23. ResultSet rs = s.executeQuery("SELECT * FROM test.amigos WHERE amigos.nombre = 'Matias'"); // Crea un objeto para almacenar resultados y ejecuta una consulta
  24.  
  25. String datosAmigo [] = new String[2];
  26. datosAmigo[0] = "Juan";
  27. datosAmigo[1] = "3487523145";
  28. actualizarBasedeDatos(datosAmigo,s);
  29. s.executeUpdate("delete FROM TEST.AMIGOS WHERE AMIGOS.NOMBRE = 'JUAN'");
  30. leerConsulta(rs);
  31. conexion.close();
  32.  
  33.  
  34. }
  35.  
  36. private static void actualizarBasedeDatos(String [] datosAmigo, Statement s) throws SQLException {
  37. s.executeUpdate("INSERT INTO test.amigos (nombre, telefono) VALUES ('"+datosAmigo[0]+"', '"+datosAmigo[1]+"')"); //Acutaliza la base
  38.  
  39. }
  40.  
  41. private static void leerConsulta(ResultSet rs){
  42. try {
  43. while (rs.next()) {
  44. System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); // Lee de la base la consulta realizada
  45. }
  46. } catch (SQLException ex) {
  47. Logger.getLogger(amigos.class.getName()).log(Level.SEVERE, null, ex);
  48. }
  49. }
  50.  
  51.  
  52. }
Add Comment
Please, Sign In to add comment