Skip to content

Instantly share code, notes, and snippets.

@MarioCares
Created November 19, 2024 02:29
Show Gist options
  • Save MarioCares/aba00e0be294478d8521f5b7194390d8 to your computer and use it in GitHub Desktop.
Save MarioCares/aba00e0be294478d8521f5b7194390d8 to your computer and use it in GitHub Desktop.
// EN EVENTO BTN GUARDAR
String url = "jdbc:mysql://localhost:3306/test";
try {
// Cargar el driver JDBC
Class.forName("com.mysql.cj.jdbc.Driver");
// Establecer la conexión
Connection connection = DriverManager.getConnection(url, "root", "UST");
System.out.println("Conectado a BD");
String sql = "INSERT INTO test.usuario (run, nombreCompleto, edad) \n" +
" VALUES (" + txtRun.getText() + ", '" + txtNombreCompleto.getText() + "', " + txtEdad.getText() + ")";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
System.out.println("Se han registrado los datos.");
sql = "SELECT * FROM usuario";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("RUN: " + resultSet.getInt("run"));
System.out.println("Nombre Completo: " + resultSet.getString("nombreCompleto"));
System.out.println("Edad: " + resultSet.getInt("edad"));
}
Persona p = new Persona(
Integer.valueOf(txtRun.getText()),
Integer.valueOf(txtEdad.getText()),
txtNombreCompleto.getText()
);
System.out.println(p);
} catch (ClassNotFoundException ex) {
System.out.println("No existe el driver de conexión. " + ex.getMessage());
} catch (SQLException ex) {
System.out.println("Error al conectar a BD. " + ex.getMessage());
} catch (Exception ex) {
System.out.println("Error al instanciar persona. " + ex.getMessage());
}
// ---------------
// EN EVENTO BTN ELIMINAR
String url = "jdbc:mysql://localhost:3306/test";
try { // [email protected]
// Cargar el driver JDBC
Class.forName("com.mysql.cj.jdbc.Driver");
// Establecer la conexión
Connection connection = DriverManager.getConnection(url, "root", "UST");
System.out.println("Conectado a BD");
String sql = "DELETE FROM usuario WHERE run = " + txtRunEliminar.getText();
System.out.println(sql);
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
System.out.println("Se ha eliminado el registro.");
sql = "SELECT * FROM usuario";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("RUN: " + resultSet.getInt("run"));
System.out.println("Nombre Completo: " + resultSet.getString("nombreCompleto"));
System.out.println("Edad: " + resultSet.getInt("edad"));
}
} catch (ClassNotFoundException ex) {
System.out.println("No existe el driver de conexión. " + ex.getMessage());
} catch (SQLException ex) {
System.out.println("Error al conectar a BD. " + ex.getMessage());
} catch (Exception ex) {
System.out.println("Error al instanciar persona. " + ex.getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment