Last active
December 11, 2021 15:16
-
-
Save PramodKumarYadav/a4110f6390c20985d3924558e96f9fc4 to your computer and use it in GitHub Desktop.
A DBConnection class to connect to any database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.powertester.yourprojectname.database; | |
import com.typesafe.config.Config; | |
import lombok.extern.slf4j.Slf4j; | |
import org.powertester.yourprojectname.config.TestEnvironment; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
/** | |
* For this to work: | |
* 1) You would need the maven dependency of the database type driver you need to connect (MySQL, PostGre, MongoDb). | |
* 2) Configuration to be stored/fetched from a config system (I used typesafe here but you can use a config system of your choice). | |
* 3) A logger (I used Slf4j), but you can use whatever you like. | |
* Another generic rule to follow: The class calling the connection must close the connection. | |
* (object -> dbConnection.getConnection() will give connection to close). | |
*/ | |
@Slf4j | |
public class DBConnection { | |
private Connection connection; | |
private static final Config config = TestEnvironment.getConfig(); | |
private static final String DB_CONNECTION_STRING = config.getString("DB_CONNECTION_STRING"); | |
private static final String DB_USER = config.getString("DB_USER"); | |
private static final String DB_PASSWORD = config.getString("DB_PASSWORD"); | |
public DBConnection(String database) { | |
setConnection(database); | |
} | |
private void setConnection(String database) { | |
try { | |
connection = DriverManager.getConnection(DB_CONNECTION_STRING + database, DB_USER, DB_PASSWORD); | |
if (connection != null) { | |
log.debug("DBConnection Successful!"); | |
} | |
} catch (SQLException e) { | |
throw new IllegalStateException("DBConnection failed!", e); | |
} | |
} | |
public Connection getConnection(){ | |
return connection; | |
} | |
public ResultSet getResultSet(String sql) { | |
try { | |
return connection.prepareStatement(sql).executeQuery(); | |
} catch (SQLException e) { | |
throw new IllegalStateException("executeQuery failed!", e); | |
} | |
} | |
public void setResultSet(String sql) { | |
try { | |
connection.prepareStatement(sql).executeUpdate(); | |
} catch (SQLException e) { | |
throw new IllegalStateException("executeUpdate failed!", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example 02: You are executing a query
(Insert, Update or Delete)
and have no results to work with.