Advertisement
Guest User

SqlConnector

a guest
Oct 30th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. package md.sw.util.sql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. public class SqlConnector {
  10.     private final String url;
  11.     private final String user;
  12.     private final String password;
  13.     private Connection connection;
  14.    
  15.     private SqlConnector(final String url, final String user, final String password) {
  16.         this.url = url;
  17.         this.user = user;
  18.         this.password = password;
  19.     }
  20.    
  21.     public static SqlConnector build(String url, String user, String password) {
  22.         return new SqlConnector(url, user, password);
  23.     }
  24.    
  25.     public PreparedStatement preparedStatement(String sql) throws SQLException {
  26.         return connection.prepareStatement(sql);
  27.     }
  28.    
  29.     public int insert(String sql) throws SQLException {
  30.         if(isConnected()) {
  31.             return preparedStatement(sql).executeUpdate();
  32.         }
  33.         return 0;
  34.     }
  35.    
  36.     public ResultSet select(String sql) throws SQLException {
  37.         if(isConnected()) {
  38.             return preparedStatement(sql).executeQuery();
  39.         }
  40.         return null;
  41.     }
  42.    
  43.     public void open() throws SQLException {
  44.         if(!isConnected()) {
  45.             connection = DriverManager.getConnection(url, user, password);
  46.         }
  47.     }
  48.    
  49.     public void close() throws SQLException {
  50.         if(isConnected()) {
  51.             connection.close();
  52.         }
  53.     }
  54.    
  55.     public boolean isConnected() {
  56.         return connection != null;
  57.     }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement