Connecting to a database in a decoupled manner-by reading a configuration file

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.