Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- public class Exemplo {
- static Connection conexao = null;
- public static void main(String args[]){
- try {
- // Registra o driver
- Class.forName("org.postgresql.Driver");
- conectarBancoDados();
- listarClientesContas();
- executaTransferencia(123456, 563346, 200.0);
- listarClientesContas();
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e1) {
- e1.printStackTrace();
- }
- }
- private static void listarClientesContas() throws SQLException {
- Statement stmt = conexao.createStatement();
- ResultSet resultado = stmt.executeQuery(
- "select c.nome, cc.numero_conta, cc.saldo " +
- "from correntista as c, conta as cc " +
- "where c.cnpjcpf = cc.cnpjcpf_cliente ");
- while (resultado.next()) { // Iterador
- System.out.println("Cliente/conta: " +
- resultado.getString(1) + ", " +
- resultado.getString(2) + ", " +
- resultado.getString(3));
- }
- resultado = stmt.executeQuery(
- "select sum(saldo) " +
- "from conta");
- if (resultado.next()){
- System.out.println("Total de depósitos: " + resultado.getString(1));
- }
- }
- private static void conectarBancoDados() throws SQLException {
- String url = "jdbc:postgresql://localhost:5432/bancario";
- conexao = DriverManager.getConnection(url,"postgres", "postgres");
- }
- private static void executaTransferencia(double origem, double destino, double valor) throws SQLException {
- String consultaPreparada = "update conta set saldo = saldo + ? " +
- "where numero_conta = ?";
- System.out.println("Transferência: CC " + origem + " -> CC " + destino + " = R$ " + valor);
- conexao.setAutoCommit( false );
- PreparedStatement stmt = conexao.prepareStatement(consultaPreparada);
- stmt.setDouble( 1, -valor );
- stmt.setDouble( 2, origem );
- stmt.executeUpdate();
- stmt.setDouble( 1, valor );
- stmt.setDouble( 2, destino );
- stmt.executeUpdate();
- stmt.close();
- conexao.commit();
- conexao.setAutoCommit( true );
- }
- }
Add Comment
Please, Sign In to add comment