Advertisement
Guest User

Untitled

a guest
Aug 19th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.26 KB | None | 0 0
  1. package util;
  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 DBWorker {
  10.    
  11.     // Количество рядов таблицы, затронутых последним запросом.
  12.     private Integer affected_rows = 0;
  13.    
  14.     // Значение автоинкрементируемого первичного ключа, полученное после
  15.     // добавления новой записи.
  16.     private Integer last_insert_id = 0;
  17.  
  18.     // Указатель на экземпляр класса.
  19.     private static DBWorker instance = null;
  20.    
  21.     // Метод для получения экземпляра класса (реализован Singleton).
  22.     public static DBWorker getInstance()
  23.     {
  24.         if (instance == null)
  25.         {
  26.             instance = new DBWorker();
  27.         }
  28.    
  29.         return instance;
  30.     }
  31.    
  32.     // "Заглушка", чтобы экземпляр класса нельзя было получить напрямую.
  33.     private DBWorker()
  34.     {
  35.      // Просто "заглушка".           
  36.     }
  37.    
  38.     // Выполнение запросов на выборку данных.
  39.     public ResultSet getDBData(String query)
  40.     {
  41.         Statement statement;
  42.         Connection connect;
  43.         try
  44.         {
  45.             Class.forName("com.mysql.jdbc.Driver").newInstance();
  46.             connect = DriverManager.getConnection("jdbc:mysql://localhost/phonebook?user=root&password=123456&useUnicode=true&characterEncoding=UTF-8&characterSetResults=utf8&connectionCollation=utf8_general_ci");
  47.             statement = connect.createStatement();
  48.             ResultSet resultSet = statement.executeQuery(query);
  49.             return resultSet;
  50.         }
  51.         catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e)
  52.         {
  53.             e.printStackTrace();
  54.         }
  55.        
  56.         System.out.println("null on getDBData()!");
  57.         return null;
  58.  
  59.     }
  60.    
  61.     // Выполнение запросов на модификацию данных.
  62.     public Integer changeDBData(String query)
  63.     {
  64.         Statement statement;
  65.         Connection connect;
  66.         try
  67.         {
  68.             Class.forName("com.mysql.jdbc.Driver").newInstance();
  69.             connect = DriverManager.getConnection("jdbc:mysql://localhost/phonebook?user=root&password=123456&useUnicode=true&characterEncoding=UTF-8&characterSetResults=utf8&connectionCollation=utf8_general_ci");
  70.             statement = connect.createStatement();
  71.             this.affected_rows = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
  72.        
  73.             // Получаем last_insert_id() для операции вставки.
  74.             ResultSet rs = statement.getGeneratedKeys();
  75.             if (rs.next()){
  76.                 this.last_insert_id = rs.getInt(1);
  77.             }
  78.            
  79.             return this.affected_rows;
  80.         }
  81.         catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e)
  82.         {
  83.             e.printStackTrace();
  84.         }
  85.        
  86.         System.out.println("null on changeDBData()!");
  87.         return null;
  88.     }
  89.  
  90.     // +++++++++++++++++++++++++++++++++++++++++++++++++
  91.     // Геттеры и сеттеры.
  92.     public Integer getAffectedRowsCount()
  93.     {
  94.         return this.affected_rows;
  95.     }
  96.    
  97.     public Integer getLastInsertId()
  98.     {
  99.         return this.last_insert_id;
  100.     }
  101.     // Геттеры и сеттеры.
  102.     // -------------------------------------------------
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement