Created
April 18, 2014 12:08
-
-
Save azakordonets/11040670 to your computer and use it in GitHub Desktop.
Class for DbConnection handiling
This file contains 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 Base.db_connection; | |
import org.json.JSONObject; | |
import java.sql.*; | |
import static Base.TestPropertiesLoader.getDbConnectionDetails; | |
public class DbConnection { | |
public Connection con = null; | |
public Statement statement= null; | |
JSONObject connnDetails; | |
public DbConnection(String dbName) { | |
try { | |
connnDetails = getDbConnectionDetails(dbName); | |
Class.forName(connnDetails.getString("driver")); | |
con = DriverManager.getConnection(connnDetails.getString("dbname"), | |
connnDetails.getString("username"), | |
connnDetails.getString("password")); | |
statement= con.createStatement(); | |
System.out.println ("Database connection established"); | |
} | |
catch (Exception e) { | |
System.out.println(e.getMessage()); | |
e.printStackTrace(); | |
} | |
} | |
public ResultSet query(String query){ | |
System.out.println("capturing from database " +query); | |
ResultSet result = null; | |
try { | |
result = statement.executeQuery(query); | |
} catch (SQLException e) { | |
System.out.println("Error during query execution + " +e.getMessage()); | |
e.printStackTrace(); | |
} | |
if (result == null){ | |
throw new NullPointerException("Query resulted in null. Check DB connection and query itself"); | |
} else { | |
return result; | |
} | |
} | |
public void terminateConnection(){ | |
try { | |
con.close(); | |
} catch (SQLException e) { | |
System.out.println("Couldn't terminate connection or some other error appeared "+e.getMessage()); | |
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment