Advertisement
Guest User

MySQL.java

a guest
Jan 8th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.function.Consumer;
  7. import java.util.function.Function;
  8.  
  9. public class MySQL {
  10.  
  11. private static Connection conn;
  12.  
  13. public void connect(String host, String database, int port, String user, String password){
  14. if(!isConnected()){
  15. try {
  16. conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user, password);
  17. System.out.println("Connexion etablie avec la base de donnees");
  18. } catch (SQLException e) {
  19. e.printStackTrace();
  20. System.out.println("Connexion refuse avec la base de donnees");
  21. }
  22. }
  23. }
  24.  
  25. public void disconnect(){
  26. if(isConnected()){
  27. try {
  28. conn.close();
  29. } catch (SQLException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34.  
  35. public static Connection getConnection(){
  36. return conn;
  37. }
  38.  
  39. public void update(String qry){
  40. try {
  41. PreparedStatement s = getConnection().prepareStatement(qry);
  42. s.executeUpdate();
  43. } catch(Exception e){
  44. e.printStackTrace();
  45. }
  46. }
  47.  
  48. public Object query(String qry, Function<ResultSet, Object> consumer){
  49. try {
  50. PreparedStatement s = getConnection().prepareStatement(qry);
  51. ResultSet rs = s.executeQuery();
  52. return consumer.apply(rs);
  53. } catch(SQLException e){
  54. throw new IllegalStateException(e.getMessage());
  55. }
  56. }
  57.  
  58. public void query(String qry, Consumer<ResultSet> consumer){
  59. try {
  60. PreparedStatement s = getConnection().prepareStatement(qry);
  61. ResultSet rs = s.executeQuery();
  62. consumer.accept(rs);
  63. } catch(SQLException e){
  64. throw new IllegalStateException(e.getMessage());
  65. }
  66. }
  67.  
  68. public boolean isConnected(){
  69. try {
  70. if((conn == null) || (conn.isClosed()) || (conn.isValid(5))){
  71. return false;
  72. }
  73. return true;
  74. } catch (SQLException e) {
  75. e.printStackTrace();
  76. }
  77. return false;
  78. }
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement