package utils.jdbc;import java.io.ioexception;import java.io.inputstream;import java.sql.connection;import java.sql.drivermanager;import java.sql.preparedstatement;import java.sql.resultset;import java.sql.sqlexception;import java.util.properties;public class dbutils {private connection conn;/** * sets the type of the database by reading the parameters of the utils.properties under the Classpath * @return conn Returns a connection * @throws IOException throws an IO exception * @ author Schjering * Time: December 7, 2015 */public connection getconnection () throws ioexception{/* * declares four parameters for * database driver *jdbc * database user name * database password */string driver = null; string url = null; string username = null; string password = null;//reads the configuration file Inputstream in = getclass () in the input stream mode. getClassLoader (). getResourceAsStream ("Utils.propErties "); Properties properties = new properties ();p roperties.load (in), //load/* * Read the values of individual parameters */driver = properties.getproperty ("Driver") from the configuration file;url = Properties.getproperty ("url"), Username = properties.getproperty ("username");p assword = Properties.getproperty ("password"); Try {class.forname (driver);conn = Drivermanager.getconnection (Url,username,password);} catch (exception e) {e.printstacktrace ();} Return conn;} Public void releaseconn (connection conn,resultset rs,preparedstatement pstm) {try {if (conn != null) {conn.close ();}} catch (sqlexception e) {e.printstacktrace ();} Try {if (rs != null) {rs.close ();}} catch (sqlexception e) {e.printstacktrace ();} Try {if (pstm != null) {pstm.close ();}} catch (sqlexception e) {e.printstacktrace ();}}
Connecting to a database in a decoupled manner-by reading a configuration file