Guest User

Conect

a guest
Jun 5th, 2017
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. package com.vitindeveloper.sql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. public class MySQL {
  10.  
  11. private String HOST = "";
  12. private String DATABASE = "";
  13. private String USER = "";
  14. private String PASSWORD = "";
  15.  
  16. private Connection con;
  17.  
  18. public MySQL(String host, String database, String user, String password) {
  19. this.HOST = host;
  20. this.DATABASE = database;
  21. this.USER = user;
  22. this.PASSWORD = password;
  23.  
  24. connect();
  25. }
  26.  
  27. protected void connect() {
  28. try {
  29. con = DriverManager.getConnection("jdbc:mysql://" + HOST + ":3306/" + DATABASE + "?autoReconnect=true",
  30. USER, PASSWORD);
  31. System.out.println("[MySQL] Conexão com o MYSQL iniciada com sucesso!");
  32. } catch (SQLException e) {
  33. System.out.println("[MySQL] A conexão com MYSQL deu erro: " + e.getMessage());
  34. }
  35. }
  36.  
  37. public void close() {
  38. try {
  39. if (con != null) {
  40. con.close();
  41. System.out.println("[MySQL] Conexão com MYSQL fechada com sucesso!");
  42. }
  43. } catch (SQLException e) {
  44. System.out.println("[MySQL] Falha ao terminar a conexão com o MYSQL: " + e.getMessage());
  45. }
  46. }
  47.  
  48. public void update(String qry) {
  49. try {
  50. Statement st = con.createStatement();
  51. st.executeUpdate(qry);
  52. st.close();
  53. } catch (SQLException e) {
  54. connect();
  55. System.err.println(e);
  56. }
  57. }
  58.  
  59. public ResultSet query(String qry) {
  60. ResultSet rs = null;
  61. try {
  62. Statement st = con.createStatement();
  63. rs = st.executeQuery(qry);
  64. } catch (SQLException e) {
  65. connect();
  66. System.err.println(e);
  67. }
  68. return rs;
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment