Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package util.sql;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import com.google.common.base.Preconditions;
- public class SqlConnector {
- private final String url;
- private final String user;
- private final String password;
- private Connection connection;
- SqlConnector(final String url, final String user, final String password) {
- Preconditions.checkNotNull(url, "Url cannot be null");
- this.url = url;
- this.user = user;
- this.password = password;
- }
- public static SqlConnector forSql(String url, String user, String password) {
- return new SqlConnector(url, user, password);
- }
- public String getUrl() {
- return url;
- }
- public String getUser() {
- return user;
- }
- public String getPassword() {
- return password;
- }
- public Connection getConnection() {
- return connection;
- }
- public void openConnection() throws SQLException {
- if(!isConnected()) {
- connection = DriverManager.getConnection(getUrl(), getUser(), getPassword());
- }
- }
- public void closeConnection() throws SQLException {
- if(isConnected()) {
- getConnection().close();
- }
- }
- public int update(String query) throws SQLException {
- return connection.prepareStatement(query).executeUpdate();
- }
- public ResultSet select(String query) throws SQLException {
- return connection.prepareStatement(query).executeQuery();
- }
- public boolean isConnected() {
- return connection != null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement