Guest User

Untitled

a guest
Jan 4th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3. public class Exemplo {
  4.  
  5. static Connection conexao = null;
  6.  
  7. public static void main(String args[]){
  8.  
  9.  
  10. try {
  11.  
  12. // Registra o driver
  13. Class.forName("org.postgresql.Driver");
  14.  
  15. conectarBancoDados();
  16.  
  17. listarClientesContas();
  18.  
  19. executaTransferencia(123456, 563346, 200.0);
  20.  
  21. listarClientesContas();
  22.  
  23.  
  24. } catch (SQLException e) {
  25. e.printStackTrace();
  26. } catch (ClassNotFoundException e1) {
  27. e1.printStackTrace();
  28. }
  29.  
  30. }
  31.  
  32. private static void listarClientesContas() throws SQLException {
  33.  
  34. Statement stmt = conexao.createStatement();
  35. ResultSet resultado = stmt.executeQuery(
  36. "select c.nome, cc.numero_conta, cc.saldo " +
  37. "from correntista as c, conta as cc " +
  38. "where c.cnpjcpf = cc.cnpjcpf_cliente ");
  39.  
  40. while (resultado.next()) { // Iterador
  41. System.out.println("Cliente/conta: " +
  42. resultado.getString(1) + ", " +
  43. resultado.getString(2) + ", " +
  44. resultado.getString(3));
  45. }
  46.  
  47. resultado = stmt.executeQuery(
  48. "select sum(saldo) " +
  49. "from conta");
  50. if (resultado.next()){
  51. System.out.println("Total de depósitos: " + resultado.getString(1));
  52. }
  53. }
  54.  
  55. private static void conectarBancoDados() throws SQLException {
  56.  
  57. String url = "jdbc:postgresql://localhost:5432/bancario";
  58. conexao = DriverManager.getConnection(url,"postgres", "postgres");
  59. }
  60.  
  61. private static void executaTransferencia(double origem, double destino, double valor) throws SQLException {
  62.  
  63. String consultaPreparada = "update conta set saldo = saldo + ? " +
  64. "where numero_conta = ?";
  65.  
  66. System.out.println("Transferência: CC " + origem + " -> CC " + destino + " = R$ " + valor);
  67. conexao.setAutoCommit( false );
  68. PreparedStatement stmt = conexao.prepareStatement(consultaPreparada);
  69.  
  70. stmt.setDouble( 1, -valor );
  71. stmt.setDouble( 2, origem );
  72. stmt.executeUpdate();
  73.  
  74. stmt.setDouble( 1, valor );
  75. stmt.setDouble( 2, destino );
  76. stmt.executeUpdate();
  77.  
  78. stmt.close();
  79. conexao.commit();
  80. conexao.setAutoCommit( true );
  81.  
  82. }
  83. }
Add Comment
Please, Sign In to add comment