Advertisement
Guest User

Untitled

a guest
Dec 21st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. public class Conexao
  2. {
  3. private static final String DRIVER="com.mysql.jdbc.Driver",URL="jdbc:mysql://localhost:3306/banco_dados",USUARIO="root",SENHA="root";
  4.  
  5. public static Connection obter()
  6. {
  7. try
  8. {
  9. Class.forName(DRIVER);
  10. return DriverManager.getConnection(URL, USUARIO, SENHA);
  11. }
  12. catch (ClassNotFoundException|SQLException ex)
  13. {
  14. JOptionPane.showMessageDialog(null, "Erro ao estabelecer conexão com o MySQL.");
  15. }
  16. return null;
  17. }
  18.  
  19. public static void fechar(Connection c)
  20. {
  21. try
  22. {
  23. if (c != null)
  24. c.close();
  25. }
  26. catch (SQLException ex)
  27. {
  28. JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
  29. }
  30. }
  31.  
  32. public static void fechar(Connection c, PreparedStatement ps)
  33. {
  34. fechar(c);
  35. try
  36. {
  37. if (ps != null)
  38. ps.close();
  39. }
  40. catch (SQLException ex)
  41. {
  42. JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
  43. }
  44. }
  45.  
  46. public static void fechar(Connection c, PreparedStatement ps, ResultSet rs)
  47. {
  48. fechar(c,ps);
  49. try
  50. {
  51. if (rs != null)
  52. rs.close();
  53. }
  54. catch (SQLException ex)
  55. {
  56. JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
  57. }
  58. }
  59. }
  60.  
  61. public class UsuarioDAO
  62. {
  63. public static void inserir(Usuario usuario)
  64. {
  65. Connection c=Conexao.obter();
  66. PreparedStatement ps=null;
  67. try
  68. {
  69. ps=c.prepareStatement("insert into usuarios(nome,senha) values(?,?)");
  70. ps.setString(1,usuario.getNome());
  71. ps.setBytes(2,usuario.getSenha());
  72. ps.executeUpdate();
  73. }
  74. catch (SQLException ex)
  75. {
  76. JOptionPane.showMessageDialog(null,"Erro ao inserir dados no MySQL.");
  77. }
  78. finally
  79. {
  80. Conexao.fechar(c,ps);
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement