Advertisement
Guest User

SqlConnector

a guest
Oct 19th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. package util.sql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7.  
  8. import com.google.common.base.Preconditions;
  9.  
  10. public class SqlConnector {
  11.     private final String url;
  12.     private final String user;
  13.     private final String password;
  14.     private Connection connection;
  15.    
  16.     SqlConnector(final String url, final String user, final String password) {
  17.         Preconditions.checkNotNull(url, "Url cannot be null");
  18.         this.url = url;
  19.         this.user = user;
  20.         this.password = password;
  21.     }
  22.    
  23.     public static SqlConnector forSql(String url, String user, String password) {
  24.         return new SqlConnector(url, user, password);
  25.     }
  26.    
  27.     public String getUrl() {
  28.         return url;
  29.     }
  30.    
  31.     public String getUser() {
  32.         return user;
  33.     }
  34.    
  35.     public String getPassword() {
  36.         return password;
  37.     }
  38.    
  39.     public Connection getConnection() {
  40.         return connection;
  41.     }
  42.    
  43.     public void openConnection() throws SQLException {
  44.         if(!isConnected()) {
  45.             connection = DriverManager.getConnection(getUrl(), getUser(), getPassword());
  46.         }
  47.     }
  48.    
  49.     public void closeConnection() throws SQLException {
  50.         if(isConnected()) {
  51.             getConnection().close();
  52.         }
  53.     }
  54.    
  55.     public int update(String query) throws SQLException {
  56.         return connection.prepareStatement(query).executeUpdate();
  57.     }
  58.    
  59.     public ResultSet select(String query) throws SQLException {
  60.         return connection.prepareStatement(query).executeQuery();
  61.     }
  62.    
  63.     public boolean isConnected() {
  64.         return connection != null;
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement