daily pastebin goal
40%
SHARE
TWEET

Untitled

a guest Jun 30th, 2018 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package model;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import org.hibernate.Session;
  16.  
  17. /**
  18.  *
  19.  * @author Henri
  20.  */
  21. public class PessoaDAO {
  22.     String endereco = "jdbc:mysql://localhost:3306/aulapoo";
  23.     String comando = "insert into pessoa(codigo,nome) values(?,?)";
  24.    
  25.     Connection conn = null;
  26.    
  27.     public static void salvar(Pessoa p)
  28.     {
  29.         Session session = null;
  30.         try {
  31.             session = HibernateUtil.getSessionFactory().openSession();
  32.             session.beginTransaction();
  33.             session.save(p);
  34.             session.getTransaction().commit();
  35.         } catch (Exception e) {
  36.             System.out.println(e.getMessage());
  37.         }
  38.         finally {
  39.             if(session != null)
  40.                 session.close();
  41.         }
  42.     }
  43.    
  44.     public static List<Pessoa> listar()
  45.     {
  46.         ArrayList<Pessoa> pessoas = new ArrayList<Pessoa>();
  47.         String sql = "select * from pessoa";
  48.         Connection conn = null;
  49.        
  50.         try{
  51.             String url ="jdbc:mysql://localhost:3306/aulapoo";
  52.             conn = DriverManager.getConnection(url,"root","");
  53.            
  54.             PreparedStatement pst = conn.prepareStatement(sql);
  55.             ResultSet rs = pst.executeQuery();
  56.             while(rs.next())
  57.             {
  58.                 Pessoa p = new Pessoa();
  59.                 p.setCodigo(rs.getInt("codigo"));
  60.                 p.setNome(rs.getString("nome"));
  61.                 pessoas.add(p);
  62.             }
  63.         }
  64.         catch (SQLException e){
  65.             throw new RuntimeException(e);
  66.         }
  67.         finally{
  68.             try{
  69.                 if(conn != null && !conn.isClosed())
  70.                     conn.close();
  71.             } catch (SQLException e){
  72.                 e.printStackTrace();
  73.             }
  74.         }
  75.         return pessoas;
  76.     }
  77.    
  78. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top